Home / How to check if a Javascript function exists

How to check if a Javascript function exists

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.