If you try to call a function that doesn’t exists, JavaScript will throw an error “Uncaught ReferenceError: function is not defined”. To prevent this error, you can typeof
to check if a function exists before calling it.
What is typeof Operator
The typeof
operator returns a string indicating the type of the unevaluated operand. Below is a list of possible values it will return:
- symbol
- string
- bigint
- number
- boolean
- undefined
- function
In another word, typeof will only return “function” if the JavaScript function exists.
How to Use typeof to Check if a Function Exists
typeof
is very easy to use. Lete’s look at the following example, we have a JavaScript function called displayMessage, and we are checking if typeof
operator returns “function” before calling it.
// check if function exists
function displayMessage(){
console.log("typeof Example");
}
if(typeof printMessage === "function"){
displayMessage();
}
How to Check if a Function Exists in Parent Window
typeof
operator can be use to check a function in the parent windows, see below for an example:
// check if function exists in parent windows
if(typeof parent.printMessage === "function"){
displayMessage();
}