Search code examples
javascripttypestypechecking

Why use toString() to typecheck args that you can check with typeof?


I understand why you need to use Object.prototype.toString() or String() for typechecking arrays, but isn't typeof sufficient for typechecking functions and strings? For example the polyfill on MDN for Array.isArray uses:

Object.prototype.toString.call(arg) == '[object Array]';

It's pretty clear in the case of arrays because you can't use typeof to check for arrays. Valentine uses instanceof for this:

ar instanceof Array

But for strings/functions/booleans/numbers, why not use typeof?

jQuery and Underscore both use something like this to check for functions:

Object.prototype.toString.call(obj) == '[object Function]';

Isn't that equivalent to doing this?

typeof obj === 'function'

or even this?

obj instanceof Function

Solution

  • Ok I think I figured out why you see the toString usage. Consider this:

    var toString = Object.prototype.toString;
    var strLit = 'example';
    var strStr = String('example')​;
    var strObj = new String('example');
    
    console.log(typeof strLit); // string    
    console.log(typeof strStr); // string
    console.log(typeof strObj); // object
    
    console.log(strLit instanceof String); // false
    console.log(strStr instanceof String); // false
    console.log(strObj instanceof String); // true
    
    console.log(toString.call(strLit)); // [object String]
    console.log(toString.call(strStr)); // [object String]
    console.log(toString.call(strObj)); // [object String]