How to Check if Your Javascript Function Exists CodeUnit 28 MAR 2010

So I updated a panel generating script to adhere to some campaign rules, meaning that certain graphing functions were no longer being generated by the PHP script. Great, as easy as that I thought to myself as I patted myself on the back and uploaded the updated code, only to recoil in horror when the site stopped working correctly all of a sudden.

Debugging the errors, I discovered that the thing was falling over whenever a previously untouched bit of code was trying to reference my Javascript scripts – some of which were obviously no longer in existence!

So the question I was then left with is how to check for the existence of a function before actually calling that function, the solution to which turns out to be fairly simple.

All you need to do is this:

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

where obviously yourFunctionName is the name of the function you wish to test.

Works like a charm and after implementing this on all of my function calls, no more broken site, meaning happy me and thus a well deserved pat on the back.

Nice.

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.