2

Which is a best way to check if a variable is a function?

var cb = function () {
  return;
}

if (!!(cb && cb.constructor && cb.apply)) {
  cb.apply(somevar, [err, res]);
}
//VS
if (!!(cb && 'function' === typeof cb) {
  cb.apply(somevar, [err, res]);
}
Michael
  • 177
  • 1
  • 1
  • 10

2 Answers2

9

The most common way would be to use:

(typeof foo === 'function')

But if you want to match function-like objects (which are uncommon, but can be useful), you can check whether the object is invokable:

(foo && foo.call && foo.apply)

In most cases, you can also test the constructor (very similar to typeof):

(foo.constructor === Function)

If you want to provoke an exception, you can always:

try {
  foo();
} catch (e) {
  // TypeError: foo is not a function
}
ssube
  • 47,010
  • 7
  • 103
  • 140
0

I'd say the second one since it's the simplest, most intuitive and works .

David Haim
  • 25,446
  • 3
  • 44
  • 78