Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does UnderscoreJS use toString.call() instead of typeof?

Looking under the hood in UnderscoreJS, I see:

  _.isFunction = function(obj) {
    return toString.call(obj) == '[object Function]';
  };

  _.isString = function(obj) {
    return toString.call(obj) == '[object String]';
  };

  _.isNumber = function(obj) {
    return toString.call(obj) == '[object Number]';
  };

This seems like an odd choice. Why not just use typeof to determine whether a value is a string, function, or number? Is there a performance gain by using toString? Is typeof not supported by older browsers?

like image 642
Warren Benedetto Avatar asked May 01 '12 07:05

Warren Benedetto


2 Answers

Well actually this is because it is faster to check the [[Class]] by checking with toString. Also there could be less mistakes, since toString gives you the exact Class ...

check this :

var fn = function() { 
    console.log(typeof(arguments)) // returns object
    console.log(arguments.toString()) // returns object Arguments
}

You could see the benchmark for underscore typeof vs toString here :

http://jsperf.com/underscore-js-istype-alternatives

Also there are some github issues with better explaination :

https://github.com/documentcloud/underscore/pull/332

https://github.com/documentcloud/underscore/pull/321

EDIT 1 :

You could also check this great article :

http://javascriptweblog.wordpress.com/2011/08/08/fixing-the-javascript-typeof-operator/

like image 182
drinchev Avatar answered Nov 15 '22 21:11

drinchev


drinchev's answer is partially correct. toString is currently much slower than using typeOf in most browsers. See the 7th revision of the test he posted which uses typeOf. Both are still very fast though so in most cases this performance difference won't be noticeable and the tradeoff is worth conforming to the specs better than duck typing / typeOf.

Underscore pull request 321 (that drinchev listed) has an in-depth discussion of the tradeoffs and why they decided to use toString.

like image 20
DriverDan Avatar answered Nov 15 '22 19:11

DriverDan