How to fix ReferenceError: function is not defined
Quite simply this error happens when the function being called is null
or undefined
. This could be because the function was never initialized, or just a typo in the name. Let's look at these in more detail.
Initialization Errors
In the two examples below, the error is generated because the function doesn't exist (standalone or when calling an object). If you're calling third-party code, it could be that the script failed to load (ex. due to a network error) and the code in question assumed it would always exist.
Example
func(); // ReferenceError: func is not defined
const obj = {};
obj.func(); // ReferenceError: obj.func is not defined
Solution
Ensure any third party code is loaded correctly before calling the function. If you want to be defensive in the case of network failures (the user might be blocking that third-party script!), guard against null or undefined before calling the function:
if (func) {
func(); // no error
}
if (obj.func) {
obj.func(); // no error
}
Typos
Typos are a class of error that can be the most annoying but also the easiest to fix - just correct the typo! Modern code editors (such as VS Code) or linters (like eslint) will automatically point out typos in code. If you want to prevent typos altogether, adopting TypeScript will turn runtime errors into compile time errors.
Solution
Ensure the function name matches the definition exactly - including casing, which matters in JavaScript identifiers.