Javascript: checking if a function exists
Posted March 20, 2007
on:- In: JavaScript
- 9 Comments
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"
[…] 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’);
}
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*
1 | Coder
November 21, 2007 at 4:16 pm
it is
if(typeof (window.myFunction) == ‘function’) {
// function exists, so we can now call it
myFunction(’foo’, ‘bar’);
}