Check if a Javascript function exists, if so call it.

I had a little trouble searching for this on Google. So here’s a little Javascript gem for you.

If you want to call a Javascript function, but only if it exists, here’s one way you can do that.

function ifFnExistsCallIt(fnName)
{
   fn = window[fnName];
   fnExists = typeof fn === 'function';
   if(fnExists)
      fn();
}

I use “fn” as a variable name inplace of the word “function,” since “function” is a reserved word in Javascript.

3 thoughts on “Check if a Javascript function exists, if so call it.

  1. Here’s another approach, I recently used. Say your function is named “doMagic”. If it does not exist an empty function is called which obviously does nothing:


    (window.doMagic || function(){})(arguments...);

    Or:


    (window.doMagic || function(){})call(arguments...);

  2. I know this post is old, but it was one of the first results when I searched, but I wanted to search this simpler solution that I came up with:

    fnName && fnName();

    if fnName(the variable that holds the function closure) is not undefined, then execute it. it’s hackish, but i figure if you have a value where you expect a function, there’s bigger problems going on anyway.

Leave a Reply

Your email address will not be published.