In JavaScript, you can check whether a function is defined before calling it. This helps prevent runtime errors when a function may not exist in the current scope.
- Use the typeof operator to check whether a value is a function.
- typeof functionName === "function" returns true when the function is defined.
- It can be used with user-defined and built-in functions.
- It is useful when functions may be loaded conditionally or dynamically.
Using the typeof Operator
The typeof operator returns a string indicating the type of a value. Since JavaScript returns "function" for functions, it can be used to determine whether a function is defined.
Syntax:
typeof variableWorking:
- Use typeof with the function name.
- Compare the returned value with "function".
- If the result is "function", the function is defined and can be called.
- Otherwise, the function is not defined.
Example 1: Checking an Undefined Function
let defined = "Not defined";
if (typeof fun === "function") {
defined = "Defined";
}
console.log("Function " + defined);
Output
Function Not defined
Here, fun is not defined, so typeof fun returns "undefined" instead of throwing a ReferenceError.
Example 2: Checking a Defined Function
function fun() {
console.log("Function called");
}
let defined = "Not defined";
if (typeof fun === "function") {
defined = "Defined";
}
console.log("Function " + defined);
Output
Function Defined
Example 3: Creating a Reusable Function Check
Instead of writing the typeof condition repeatedly, we can create a helper function that checks whether a value is a function.
function isFunction(possibleFunction) {
return typeof possibleFunction === "function";
}
function fun() {}
if (isFunction(fun)) {
console.log("Function is defined");
} else {
console.log("Function is not defined");
}
Output
Function is defined
- typeof possibleFunction determines the type of the provided value.
- If the result is "function", isFunction() returns true.
- Otherwise, it returns false.
- This makes the function reusable for checking different values.