3

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]);
}
1
  • 2
    As easy as if(typeof cb == 'function') { ... } Commented Mar 26, 2015 at 14:01

2 Answers 2

10

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
}
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.