This article will describe the JavaScript “function not defined error” while it is defined.
JavaScript Function Not Defined Error (BUT IT IS DEFINED)
Sometimes, the function is defined in the code, but still, you can face the following error:
There are two main reasons why the above error occurs after defining the function, which are listed below:
Reason 1: Function is Misspelled or has Incorrect Capitalization
Sometimes, the function is called with incorrect spellings. As JavaScript is a case-sensitive language, the JavaScript interpreter could not find that and throw a “function not defined” error.
Example
First, we will define a function “summ” that returns the sum of two numbers “a” and “b”:
return a + b;
}
Call the function “summ” as “sum” by passing numbers “4” and “7”:
It will throw an error “sum is not defined”:
How to Fix it?
To fix this error, make sure that the function name is spelled properly and has the correct capitalization:
Now, the function “summ” has been successfully called and print the sum of two numbers “4” and “7”:
Reason 2: Function is Defined in a Different Scope
In JavaScript, each function has its scope, and a function can only access variables and functions that are defined within its own scope. If a function is defined in a different scope, it may not be accessible to the current scope, resulting in a “function not defined” error.
Example
Define a function “sum()” with two parameters “a” and “b” inside the function “print()”:
function sum(a, b) {
console.log(a + b);
}
}
Call the function “sum()”:
It gives an error because sum() is defined inside the print() function but accessed outside from the scope:
How to Fix it?
Ensure the function is defined in the appropriate scope and can be accessed from where it is being called. For example, if the function is defined inside another function, it may not be accessible from outside.
Call the sum() inside the print() function after defining it:
function sum(a, b) {
console.log(a + b);
}
sum(1, 4);
}
Call the print() method:
Output
Or you can also define function separately and call it in another function’s scope as follows:
console.log(a + b);
}
Here, we will call the sum() inside the print() function:
sum(5, 10);
}
Call the print() method to execute the function “sum()”:
The sum of two numbers “5” and “10” have been displayed:
We have discussed the reasons and solutions for the JavaScript “function not defined error” (but it is defined).
Conclusion
There are two main reasons why the “function not defined” error occurs after defining the function, such as “function is misspelled or has incorrect capitalization” or the “function is defined in a different scope”. This article defined the reasons and solutions for the JavaScript “function not defined error” (but it is defined).