Posts Tagged ‘tip’

Quick Tip: Checking if a javascript function exists

Tuesday, August 25th, 2009

I recently had to write a javascript function that would be used across several sites, and it would call another function that might or might not exist on any of these sites.  There are probably a couple of ways you could get around the inevitable error caused by calling a function that doesn’t exist (I’m thinking some sort of overload here), but I found that the simplest method is to wrap the function call in an if statement like so:

if(typeof myFunction == 'function') {
	myFunction();
}

Handy, huh?

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