55

I think it might be only performance case - http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/2

And seems that typeof is faster.. so my question is - which is more appropriate to use?

Kosmetika
  • 20,774
  • 37
  • 108
  • 172
  • 2
    See the answers here - http://stackoverflow.com/questions/5999998/how-can-i-check-if-a-javascript-variable-is-function-type – dsgriffin Jun 14 '13 at 12:10

2 Answers2

102

There is no reason not to use typeof.

Not only is it faster but the ECMAScript specification ensures that all functions have a type of "function" and that only functions can have a type of "function" :

enter image description here

This operator was specifically designed to get the type of a value, so why not use it ?

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758
14

Firstly, Underscore doesn't use that implementation anymore. It optimizes to typeof unless typeof /./ returns function, as it did atleast in older versions of Chrome

You can find this in the source code: http://underscorejs.org/underscore.js

// Optimize `isFunction` if appropriate.
  if (typeof (/./) !== 'function') {
    _.isFunction = function(obj) {
      return typeof obj === 'function';
    };
  }

New jsperf: http://jsperf.com/comparing-underscore-js-isfunction-with-typeof-function/3

It still shows quite a performance hit in FF (but MUCH less than the naive implementation you posted in the question), which is due to the overhead of a function call vs just inlining code.

Community
  • 1
  • 1
Dogbert
  • 212,659
  • 41
  • 396
  • 397
  • Testing in Chrome 27.0.1453.110 on Mac OS X 10.8.3 - ``typeof`` is a winner 54,472,323 ±1.45% fastest – Kosmetika Jun 14 '13 at 12:19
  • @Kosmetika, try wrapping the `typeof` into a simple function which does the same thing and compare. :) – Dogbert Jun 14 '13 at 12:20
  • but anyway why not just simply use ``typeof``? – Kosmetika Jun 14 '13 at 12:22
  • 1
    @Kosmetika, did you see the link I posted in the first sentence? For compatibility with old Google Chromes. – Dogbert Jun 14 '13 at 12:23
  • @Kosmetika There's no reason not to use typeof. In his interesting answer Dogbert points to a reason that isn't valid anymore (unless you manage to run an old version of Chrome). – Denys Séguret Jun 14 '13 at 12:24