- How to check if a JavaScript function is defined?
- Using the typeof Operator
- Syntax
- Parameters
- Example
- Using the instanceof Operator
- Syntax
- Example
- Using the try-catch block
- Syntax
- Example
- Check if Function Exists Before Calling
- Comments
- Check if Function Exists Before Calling
- Comments
- How to Check if Function Exists in JavaScript
- The try. catch Method
- The typeof Operator
How to check if a JavaScript function is defined?
In this tutorial, we will learn to check whether the JavaScript function is defined or not. If a programmer calls the JavaScript function without defining it, they will see the reference error with the message like “function is not defined.”
To overcome the problem, the programmer can check whether the function is defined and call the function.
We will look at the various approaches to check if the function is defined or not in JavaScript below.
Using the typeof Operator
In JavaScript, the typeof operator is useful to check the type of the variable, function, objects, etc. When we use the function name as the operand of the typeof variable, it returns the ‘function’ string, and we can check whether the function is defined. If function is not defined, typeof operator returns the ‘undefined’.
Syntax
Following is the syntax of the typeof operator.
let isFunction = typeof function_name === 'function'
Parameters
- function_name − It is a function name without parenthesis, for which users want to check if function is defined or not.
Example
In the example below, we will create the function named test(). We will use the typeofoperator to check whether the test() function is defined or not. If function is defined, we will call the function. Otherwise, we will print the message, like ‘function is not defined.’
html> head> /head> body> h2>Check if function is defined in Javascript./h2> h4>Check if function is defined using i> typeof operator./i>/h4> div id = "output">/div> script> var output = document.getElementById("output"); function test() output.innerHTML = "function test() is defined."; > if (typeof test === 'function') test(); > else output.innerHTML = "function is not defined."; > /script> /body> /html>
In the above output, users can see that control goes inside the if statement as function is defined and prints the message from the function.
Using the instanceof Operator
In JavaScript, the instanceof operator is used to check the type of the variables of the object types. The function, object, array, etc., are JavaScript object types. So, programmers can use it with the instanceof operator.
We will use the Function object at the right operand of the instanceof operator and the function name as the left operand. It returns true if variable is of function type otherwise false.
Syntax
Users can use the syntax below to check whether the function is defined or not using the instanceof operator
let isFunction =function_name instanceof Function;
Example
The below example demonstrates the use of the instanceof operator with the function objects. We have created the demo() function and checked if it is defined or not using the instanceof operator.
html> head> /head> body> h2>Check if function is defined in JavaScript./h2> h4>Check if function is defined using i> instanceof operator./i>/h4> div id = "output">/div> script> var output = document.getElementById("output"); function demo() output.innerHTML = "Inside the function call."; > if (demo instanceof Function) demo(); > else output.innerHTML = "function is not defined."; > /script> /body> /html>
Using the try-catch block
In JavaScript, the try-catch block is useful for error handling. JavaScript produces a reference error when the programmer calls the function without defining it. We will invoke the function call in the try block to handle the error. If the function is not defined, control automatically goes to the catch block to handle the error and terminates the program’s execution.
Syntax
Users can follow the syntax below to use the try-catch block to check function is defined or not.
try // call the function here > catch (e) // if the function is not defined, control comes here. >
Example
The below example demonstrates the use of the try-catch block with the function call. We have defined the demo() function and called the test() function from the try block. It will produce the error, and control will go into the catch block.
html> head> /head> body> h2>Check if function is defined in Javascript./h2> h4>Check if function is defined using i> try-catch /i> block./h4> div id = "output">/div> script> var output = document.getElementById("output"); function func() output.inerHTML = "Inside the function call."; > try test(); > catch (e) output.innerHTML = "Inside the catch block.
"; output.innerHTML += "function is not defined."; > /script> /body> /html>
In the above output, users can see that test() function is not defined, so control goes to the catch block and prints all messages of the catch() block.
We have learned the three different approaches to check whether the function is defined or not. The first and second approaches are pretty similar as both check the object type. The third approach doesn’t check for the type of variable, but if any error occurs while calling the function, it sends the control to catch block.
Check if Function Exists Before Calling
When using scripts that are shared between different areas of a site, there may be cases where a function is called that doesn’t exist. It makes sense on one page (the dependency is there) but not another. The difference is too slight to warrant forking the file into different versions. Instead, you can just check if the function exists before calling it to avoid the error:
if (typeof yourFunctionName == 'function')
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
Great snippet! I keep this in my list of common functions and it’s saved me a million times during development. I like to add an ‘else’ statement with an alert (or console.log()) to make the failure more visible.
if (typeof yourFunctionName == 'function') < yourFunctionName(); >else
// no error checking (yourFunctionName || Function)(); // debugging, maybe on Firefox (yourFunctionName || console.error)(); // debugging on Chrome (yourFunctionName || function()< console.error(arguments) >)();
$.isFunction(yourFunctionName)&&yourFunctionName()
yourFunctionName&&yourFunctionName()
The suggestion to check for the type to determine if something exists is questionable. If you’re at the point where you don’t even know a function exists or not and you haven’t designed the situation on purpose, something is very wrong and ill-planned. If you know you have a condition in a game or an asynchronous communication delay, where the user is allowed to check progress or what not, you plan for it and utilize a try-catch. I prefer to use a cautious trigger class to handle this so I can easily define an on event to fire when we need to respond to the alternate code path. You can always check e for the exact error with e.message. You can see that once the classes are defined the actual error handler and function call are terse, while the cautious state handling is set in a reusable class. See the code comments for usage. If you do not define your own onError event, it will fire as a classic alert and not bring down your page.
cautiousTrigger = function()<>; cautiousTrigger.prototype = < onError : function(e)< alert(e); >, trigger:function(o,func,args) < try < func.apply(o,args); return true; >catch(e) < this.onError(e); >> > someClass = function()<>; someClass.prototype = < yourFunctionName:function(arg1,arg2)< console.log(arg1,arg2); >> var attempt = new cautiousTrigger(); attempt.onError = function(e) < console.log(e.message); doSomethingElse(); >function doSomethingElse() < alert("Hey buddy! Hold your horses, we're doing something awesome."); >var someInstance = new someClass(); // the class instance exists, everything will be fine attempt.trigger(someInstance,someInstance.yourFunctionName,["arg1","arg2"]); //this trigger one will trigger the doSomethingElse function because it doesn't exist yet: attempt.trigger(someOtherInstance,someOtherInstance.yourFunctionName,["arg1","arg2"]);
If someone wishes to extend an existing object for example add a clamp() or map() function to the Number.prototype object, they could see if someone else has done such a thing using this method. I know many people that like to add those two functions because of how useful they are(including me), and it is trivial to choose this method for determining if someone else has done such a thing. People say not to extend the default objects like this in case they get updated in the future but this method would protect against that issue anyway.
Check if Function Exists Before Calling
When using scripts that are shared between different areas of a site, there may be cases where a function is called that doesn’t exist. It makes sense on one page (the dependency is there) but not another. The difference is too slight to warrant forking the file into different versions. Instead, you can just check if the function exists before calling it to avoid the error:
if (typeof yourFunctionName == 'function')
Psst! Create a DigitalOcean account and get $200 in free credit for cloud-based hosting and services.
Comments
Great snippet! I keep this in my list of common functions and it’s saved me a million times during development. I like to add an ‘else’ statement with an alert (or console.log()) to make the failure more visible.
if (typeof yourFunctionName == 'function') < yourFunctionName(); >else
// no error checking (yourFunctionName || Function)(); // debugging, maybe on Firefox (yourFunctionName || console.error)(); // debugging on Chrome (yourFunctionName || function()< console.error(arguments) >)();
$.isFunction(yourFunctionName)&&yourFunctionName()
yourFunctionName&&yourFunctionName()
The suggestion to check for the type to determine if something exists is questionable. If you’re at the point where you don’t even know a function exists or not and you haven’t designed the situation on purpose, something is very wrong and ill-planned. If you know you have a condition in a game or an asynchronous communication delay, where the user is allowed to check progress or what not, you plan for it and utilize a try-catch. I prefer to use a cautious trigger class to handle this so I can easily define an on event to fire when we need to respond to the alternate code path. You can always check e for the exact error with e.message. You can see that once the classes are defined the actual error handler and function call are terse, while the cautious state handling is set in a reusable class. See the code comments for usage. If you do not define your own onError event, it will fire as a classic alert and not bring down your page.
cautiousTrigger = function()<>; cautiousTrigger.prototype = < onError : function(e)< alert(e); >, trigger:function(o,func,args) < try < func.apply(o,args); return true; >catch(e) < this.onError(e); >> > someClass = function()<>; someClass.prototype = < yourFunctionName:function(arg1,arg2)< console.log(arg1,arg2); >> var attempt = new cautiousTrigger(); attempt.onError = function(e) < console.log(e.message); doSomethingElse(); >function doSomethingElse() < alert("Hey buddy! Hold your horses, we're doing something awesome."); >var someInstance = new someClass(); // the class instance exists, everything will be fine attempt.trigger(someInstance,someInstance.yourFunctionName,["arg1","arg2"]); //this trigger one will trigger the doSomethingElse function because it doesn't exist yet: attempt.trigger(someOtherInstance,someOtherInstance.yourFunctionName,["arg1","arg2"]);
If someone wishes to extend an existing object for example add a clamp() or map() function to the Number.prototype object, they could see if someone else has done such a thing using this method. I know many people that like to add those two functions because of how useful they are(including me), and it is trivial to choose this method for determining if someone else has done such a thing. People say not to extend the default objects like this in case they get updated in the future but this method would protect against that issue anyway.
How to Check if Function Exists in JavaScript
There are times when you get an error while calling a function that has not been defined. Here, we suggest two methods to check if the function exists.
To check if a particular function name has been defined, you can use the typeof operator:
if (typeof myFunctionName === 'function') < myFunctionName(); >
In the given case, the typeof operator will return undefined because myFunctionName() has not been defined. So, the function call inside the IF statement won’t be executed.
If the function exist, the typeof operator will return the string “function”:
Javascript typeof operator
The try. catch Method
There is also another method of try. catch statement that catches function ReferenceError errors. This approach wraps the function call inside the try block of the statement like this:
Javascript try. catch method
If the function does not exist, the error occurs.
The typeof Operator
The typeof operator gets the data type of the unevaluated operand which can be a literal or a data structure like an object, a function, or a variable. The typeof returns a string with the name of the variable type as a first parameter (object, boolean, undefined, etc.). Before ECMAScript 2015, typeof was always returned a string for any operand it was supplied with. It could never generate an error. But after the addition of let and Statements/const using typeof on let and const variables in a block before they’re declared will generate a ReferenceError.