Dave's Brain

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); } }

Add a comment

Sign in to add a comment
Copyright © 2008-2017, dave - Code samples on Dave's Brain is licensed under the Creative Commons Attribution 2.5 License. However other material, including English text has all rights reserved.