How to check if a Javascript function existsHow 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.

Get a 7-Day Free Trial to FunPass.

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:

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.

Comments

blog comments powered by Disqus