Check if Function Exists in Javascript

How to check if function exists in javascript

Javascript might not be happy if you call function before it is being created. This can happen in a couple of cases.

You might be wondering how to check if function exists in javascript before calling it.

Lets say you have a onLoad logic, and there could be function definition below it. In that case, if you try to call the function from the onLoad, it might complain as

Uncaught referenceError: functionName is not defined 

This happens only because the browser will be creating the function later and there is no precedence on this.

How to fix Uncaught referenceError: is not defined javascript error

In this case you can check if the function exists first and call it afterwards:


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

This will solve the problem. But there is a catch, you need to recall it again you make sure it is loaded.

Let me know if this solves your problem or not. I can add more based on your questions or suggestions.

Mommy look.. Upgrading jQuery breaks live :(

If you have upgraded jQuery to 1.9 then you would have dreaded Uncaught TypeError: undefined is not a function would be barking at you on your javascript console.

The fix
According to the jQuery site, you would need to replace live with on

Say if you have:

$('.selector-class-name').live('click', function(){console.log('
Applications programming is a race between software engineers, who strive to produce idiot-proof programs, and the universe which strives to produce bigger idiots. So far the Universe is winning.
Rick Cook
')});

Then you would have to change this to the new version using on as follows.
*The current on will be passed the event owner as a parameter so, we have to have a way to know the parent of the event owner, in this case the object with class selector-class-name.
If we don’t know the parent we can implement body tag

$('parent-of-object').on('click', '.selector-class-name', function(){
Applications programming is a race between software engineers, who strive to produce idiot-proof programs, and the universe which strives to produce bigger idiots. So far the Universe is winning.
Rick Cook
});

This shall take care of the problem.