This article will describe the methods to verify whether the specific function exists in the JavaScript file.
How to Check if Function Exists in JavaScript?
To verify whether the specified function is already present in JavaScript, use the following approaches:
Method 1: Check if the Function Exists in JavaScript Using the “typeof” Operator
To verify whether the function already exists in script or not, use the “typeof” operator. It returns the data type of a value or expression and outputs a string indicating the operand type, such as number, string, function, and so on.
Syntax
Follow the given syntax of the “typeof” operator to determine whether the function exists or not:
//....
}
Or also you can use the below-mentioned syntax:
//....
}
Example
Define a function “testing” in a JavaScript file:
console.log("Welcome to LinuxHint");
}
Now, verify whether the “testing” function is already defined or not, using the “typeof” operator. The “typeof” operator checks the type of the “testing” function. If the returned value is equivalent to the “function, it will print the “The testing() function exists in the JS file” message. Else, “The testing() function does not exist in the JS file” message will be displayed:
console.log("The testing() function exists in the JS file");
}
else{
console.log("The testing() function does not exist in the JS file");
}
Output
Method 2: Check if the Function Exists in JavaScript Using the “window” Object
You can also use the “window” object to check if a function exists or not. The window object serves as the browser window’s universal representation in the browser environment. It has various properties and methods for interacting with the window and its contents.
Syntax
The following syntax is utilized for determining the function exists using the “window” object:
// ...
}
Example
Here, we will verify whether the function named “testing” exists in the JavaScript file using the “window” object:
console.log("The testing() function exists in the JS file");
}
else{
console.log("The testing() function does not exist in the JS file");
}
The output indicates that the function “testing” exists in the JavaScript file:
That’s all about determining if the function exists in JavaScript.
Conclusion
To determine/check whether the function exists in JavaScript or not, use the “typeof” operator or the “window” object. The “typeof” operator is a commonly used and reliable method while you are not in the browser environment. Because, in that case, the “window” object may not be available. This article described the methods to verify whether the specific function exists in the JavaScript file or not.