Labels

Friday, 2 December 2011

How to check if a JavaScript function exists

Step 1. 
  if (FunctionName)                                                                                                                                
Functions are treated as variables in JavaScript. Step 1 checks if a variable with this name exists. If a variable or function with this name doesn't exist, FunctionName is undefined and if(FunctionName) returns false.

Step 2.
  if (typeof FunctionName == 'function')                                                                                               
This step allows us to determine if the variable is actually a function.

Combining both methods, your code checking for the existance of a JavaScript function should look like this:
  if (FunctionName && typeof FunctionName== 'function') {                                                             
        // Our function exists and we can safely use it.                                                                            
  }