Friday, 30 November 2012

Check if a javascript variable contains a function


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


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

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


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 instead of instantiating an anonymous object.


No comments:

Post a Comment