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();
}
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.
Also could be:
or if you are sure that if its exists than its a function:
Thanks, very simple and nice tip
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.
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.
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:
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:
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.
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.
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
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
Thanks
STOP USING typeof FOR JS IN THE BROWSER!… Node is ok tho ;)
THIS DOESN’T WORK IN IE8
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
You saved me a lot of time. Thank you!
Brilliant and simple, thanks to all :-)
Thanks! This method is a great alternative to
if (yourFunctionName.length) {}
, which works, but logs a console error when it evaluates to false, which you usually want to avoid in production.What if I have a code where the function name is Question_A, where the underscore is a number determined by another, random, variable. In other words, how do you insert a variable into the “if statement” for use as the function name?
In the example above, what would I do in order to make the value of the variable “Function Name” in place of the ???s.
What do you think about using “try-catch” if you are not sure whether a plugin/function is defined or not?
You should use === for equality check!
A “string-less” version:
if ( function () {return typeof (callBack ) === typeof (Function)} ){
callBack()
}
Ok, so I guess wrapping it inside a function isn’t really needed. I have this as a utility function and copied too many lines. This will work too and it’s more simple:
if(typeof callBack === typeof Function){callback}
Also
I typically like one liners. For JS:
!!maybe_defined_function && maybe_defined_function();
Sometimes this does not work with JQuery plugins. I have found that the following can work in leu.
if ( jQuery().pluginName){ code } else { more code }
when you really need to find out if there is a function with same name as a string
New optional chaining syntax:
maybeFunction?.("params as normal")