Check a function is defined in JavaScript
In JavaScript, checking if a function is defined helps prevent runtime errors before calling it. This ensures the code runs safely even if a function might not exist in the current scope.
- Use typeof functionName === "function" to verify if a function exists.
- Prevents “undefined is not a function” errors.
- Works for both user-defined and built-in functions.
- Useful in dynamic or modular code where functions may load conditionally.
JavaScript typeof Operator
The typeof operator is used to find the type of a JavaScript variable. This operator returns the type of a variable or an expression.
- Parameters: It contains a single parameter var which is a JavaScript variable.
- Return value: It returns the type of a variable or an expression.
Examples to Check a Function is Defined or Not in JavaScript
let defined = 'Not defined';
if (typeof fun === 'function') {
defined = "Defined";
}
console.log("Function " + defined);
Output
Function Not defined
Syntax:
typeof varExample 2: This example checks the type of the function, If it is a function then it is defined otherwise not defined by using typeof operator by creating a function.
function isFunction(possibleFunction) {
return typeof possibleFunction === 'function';
}
function fun() { }
let defined = 'Not defined';
if (isFunction(fun)) {
defined = "Defined";
}
console.log("Function " + defined);
Output
Function Defined