Did you get the JavaScript function not defined when you ran the code?  Or looking for how to fix the JavaScript error?

As a programmer, it’s common to come across an uncaught reference errorfunction is not defined.

In this tutorial, we will discuss why do we get this error and some ways to fix it.

Function is not defined | JavaScript

The reason for getting the error is very simple. The error occurs if you try to make a function call that you haven’t defined.

For example, see the code below-


let x = 4;
let y = 8;

sum();

Error message on console-

ReferenceError: sum is not defined

In the above code example, we did exactly the same thing, we called a function named sum(), which is not defined.

As a result, the JavaScript engine cannot find the function, giving a reference error.

How to fix the error (function not defined) in JavaScript?

1. In order to remove the error, we first need to define the function.  In our example above we need to define the sum() function.


let x = 4;
let y = 8;

// define the function
function sum(x,y){
return x+y;
}

sum();

After defining the function, if you run the JavaScript program. The function is not defined error is gone and you won’t get any error.

2. If you are still getting the same error, Make sure you check for a typo error( function name) where you have made the function call.

3. There may be a third case if you are using JavaScript within an HTML page. Make sure the function declaration is loaded before making the function call. Sometimes your function declaration may be available in a separate JS file and it might load after the function call. This will give you an error if so.

Check the order of the JS files being loaded into the DOM.

And if you find the order to be not correct, then link the Js file in the suitable order to resolve the issue.

Conclusion

Finally, If you check all the above 3 lists, you will be able to fix the function not defined error in JavaScript. Let us know in the comments if you were able to resolve the issue after reading this tutorial.

Here are other JavaScript articles-

Like this article? Follow us on Facebook and LinkedIn. You can also subscribe to our weekly Feed.