_.isFunction(a) vs. typeof a === 'function'? javascript

JavascriptPerformanceunderscore.jsTypeof

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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 ?

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionKosmetikaView Question on Stackoverflow
Solution 1 - JavascriptDenys SéguretView Answer on Stackoverflow
Solution 2 - JavascriptDogbertView Answer on Stackoverflow