Dave's Brain

Browse - programming tips - javascript check if a function exists

Date: 2009nov9
Language: javaScript

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);
		}
	}
What this info useful to you? You can donate to say thanks

Add a comment

Sign in to add a comment
Copyright © 2008-2010, 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.