How to check if a Javascript function exists
Posted July 5th, 2008 in Javascript
Sometimes you might want to call a function in Javascript but check if the function exists before calling it. This is very simple and is covered in this post.
You can test if a function exists in Javascript by simply testing for the name of it in an if() conditional. One thing to be aware of is that you can't test for the function name by itself (well you can, but if it doesn't exist the Javascript will error out); it's a method of the window object so you need to test for window.function_name like so, where some_function_name_here is the name of the function you wish to test for:
if(window.some_function_name_here) ...
A full Javascript code example is shown below, which tests for both the "foo" and "bar" functions and then writes out to the HTML whether they exist or not.
<script language="javascript" type="text/javascript">
function foo() {
}
if(window.foo) {
document.writeln('foo exists<br />');
}
else {
document.writeln('foo does not exist<br />');
}
if(window.bar) {
document.writeln('bar exists<br />');
}
else {
document.writeln('bar does not exist<br />');
}
</script>
This will output:
foo exists bar does not exist
So just remember to test for window.function_name and you can't go wrong.
Related posts:
- Using setTimeout() with Javascript (Tuesday, January 27th 2009)
- Find the index of a string within a string with Javascript (Friday, November 28th 2008)
- Opening a new window with Javascript (Saturday, November 22nd 2008)
- Javascript getYear fix (Wednesday, August 13th 2008)
- Clearing the default value of text input with Javascript (Tuesday, June 17th 2008)
- Testing if a Javascript variable is defined (Tuesday, October 23rd 2007)
Share or Bookmark
Share or Bookmark this page using the following services. You will need to have an account with the selected service in order to post links or bookmark this page.
Subscribe or Follow
Subscribe via RSS or email, or follow me on Facebook or Twitter below. The RSS icon takes you through to Feedburner where you can select the service or application to use.
