Browse - Programming Tips - How can I check if a function exists (without an error message) ?

Date: 2009nov9
Language: javaScript
Platform: web

Q.  How can I check if a function exists (without an error message) ?

A.  Top level function are created in the window object so you can do:

if (window.myFunc) { // Function exists so call it myFunc() }
You can construct the function name too. For example:
var myFunc = doSomeThingToMakeTheNameOfTheFunction(); if (window[myFunc]) { // Function exists so call it window[myFunc](); }
For example, dump() exists in Firefox but not IE. So we made a function called debug() that calls the first function:
function debug(a) { if (window.dump) { dump(a); } else if (window.console && window.console.log) { window.console.log(a); } }