Grow your CSS skills. Land your dream job.

Last updated on:

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') { 
  yourFunctionName(); 
}

Comments

  1. Permalink to comment#

    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{
        alert('Check yourFunctionName!');
    }
    
  2. 
    // no error checking
    (yourFunctionName || Function)();
    
    // debugging, maybe on Firefox
    (yourFunctionName || console.error)();
    
    // debugging on Chrome
    (yourFunctionName || function(){ console.error(arguments) })();
    
  3. Also could be:

    $.isFunction(yourFunctionName)&&yourFunctionName()
    

    or if you are sure that if its exists than its a function:

    yourFunctionName&&yourFunctionName()
    
  4. TheRadio
    Permalink to comment#

    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"]);
    
  5. nathaniel
    Permalink to comment#

    I am setting up a child theme … so where do I put this snippet?

    • You’d wrap the snippet around the function you want to check. So say, for example, you have a homepage slider using flexslider or something similar. You might call that function in the global footer or in a JS file that’s shared across pages. Well, if you’re not on the homepage and there is no slider, but you’re calling it in your javascript, you’ll get an uncaught Object error in your console. So, what Chris is saying, is check to see if that function exists somewhere, if it is, then let it through, if not, don’t call it. Make sense? Here is an example using that flexslider example:

      
      $('.flexslider').flexslider({
                animation: "slide",
                touch: true,
                pauseOnHover: true,
                controlsContainer: ".flex-container"
          });
      

      So you’re calling it, in say, your global footer or shared app.js file or something on say, your contact page, but you don’t load the flexslider.js file on the contact page because there is no slider, so you’d get a javascript error. So you’d want to wrap it in Chris’ code like this:

      
      if (typeof flexslider == 'function') {
          $('.flexslider').flexslider({
                animation: "slide",
                touch: true,
                pauseOnHover: true,
                controlsContainer: ".flex-container"
          });
      }
      

      Hope that helps. Again, I’m just giving you an example using Chris’ code. Some of the other methods in this comment thread would work too.

  6. Jason Barry
    Permalink to comment#

    Shouldn’t this snippet use the ‘===’ operator instead of ‘==’?

    if (typeof yourFunctionName === ‘function’) {
    yourFunctionName();
    }

    • Jason, generally using the strict comparison operator ‘===’ is a good choice but in this case typeof always returns a string; that being the case you wouldn’t gain anything except consistency with other comparison operations in your code. I agree it’s a good habit but here it’s not required.

  7. Brad H.

    Sweet! I actually have an instance where several user controls may or may not be on a page need to initialize them in various instances so need to know if the initialization function exists or not before calling it.

    Thanks!
    Brad

  8. Permalink to comment#

    Based on a few options read above – I quite like the elegance of the running an anonymous function, and it seems (in Chrome) to be more performant.

    http://jsperf.com/optional-function-calling

  9. Aisha
    Permalink to comment#

    Thanks

  10. Cody
    Permalink to comment#

    STOP USING typeof FOR JS IN THE BROWSER!… Node is ok tho ;)

    function whatever(callback){
        return callback
            &&
            callback.constructor === Function
            &&
            callback()
            ||
            throw new Error('Toast poptarts in oven. Go ahead, toast em.');
    }
    
  11. Mike
    Permalink to comment#

    THIS DOESN’T WORK IN IE8

  12. When checking with jQuery, I do something like
    if($().functionName){
    $(“#idselected”).functionName();
    }
    Is it ok this way or is it better to still stick with the typeof

Leave a Comment

Posting Code

  • Use Markdown, and it will escape the code for you, like `<div class="cool">`.
  • Use triple-backticks for blocks of code.
    ``` 
    <div>
      <h1>multi-line block of code</h1>
      <span>be cool yo.</span>
    </div>
    ```
  • Otherwise, escape your code, like <code>&lt;div class="cool"&gt;</code>. Markdown is just easier though.

Current ye@r *

*May or may not contain any actual "CSS" or "Tricks".