Friday 30 November 2012

Check if a javascript variable contains a function

Problem:

How do I check if a value stored in a javascript variable is a function?

Solution:

While there are many ways to do this, the following code should work:

function isFunction(toCheck){
  return toCheck != null 
      && {}.toString.call(toCheck) == '[object Function]';
}

Notes:

Note that the first conditional, toCheck != null, may not be necessary. However, if null or nothing is passed to the function the result could be undefined otherwise (this was encountered, at least, in some older (or buggy?) implementations of javascript but might be a non-issue today -- feel free to test it out).

An alternative (and closely-related) method of checking is to directly call Object.prototype.toString.call() instead of instantiating an anonymous object.

References:

No comments:

Post a Comment