paul bennett

Javascript: checking if a function exists

Posted on: March 20, 2007

It’s typeof to the rescue (again)!

To check if a function exists before you try and call it (and get a nasty javasscript error), use typeof to check.

Heres something I prepared earlier:

if(typeof window.myFunction == 'function') {
// function exists, so we can now call it
myFunction('foo', 'bar');
}

——————

Want to improve your JavaScript skills? I recommend the following:

9 Responses to "Javascript: checking if a function exists"

it is

if(typeof (window.myFunction) == ‘function’) {
// function exists, so we can now call it
myFunction(’foo’, ‘bar’);
}

Nope, according to the reply I got on this post typeof is an operator, not a function, so you don’t need to wrap it in a function call.

[…] I’ve been working on a site concept which involves several pure HTML- and Javascript-based pages, to be uses as mere demonstrational material. While adding several niceties like modal windows based on my fork of Thickbox, ie. Thickbox Redux, I’ve stumbled over some strange errors Firebug throw out during the document load process.Thus I had to implement some kind of “if function exists”-magic to avoid getting errors on the debugging console (not to mention that this properly might have side-effects like totally disabling my JS efforts at all and similar worst-case scenarios) – which is quite hard to find out, I have to say.Simple, but effective solution is as follows:if(typeof yourFunctionName == ‘function’) {yourFunctionName();}Found via Idealog: Check if a Javascript Function Exists or Is Defined and (Paul Bennett) Javascript: checking if a function exists. […]

I prefer:

if(myFunction) {
// function exists, so we can now call it
myFunction(‘foo’, ‘bar’);
}

Thanks Mark, that does look nice and simple 🙂

You might want to check out this post: Javascript: testing whether elements or properties exist – the redux

Which delves a little deeper.

Thank you very much..

[…] Paul for javascript codes and besh.jquery for jQuery […]

Thank you! Just what I was looking for.

Would someone please delete post #2? WOW, a know it all in the development realm, that’s something new?

Except if the function you are trying to detect is a native function in internet explorer

for example:

typeof document.write is ‘object’ not ‘function’ in IE
but appears to be ‘function’ in all the other browsers.

*SIGH*

Leave a comment

Archives