Javascript Type Comparison

23,624

Solution 1

To just compare types, one would think typeof would be the right tool

typeof [] === typeof ['1','2','3']; // true, both are arrays

Note that null, arrays etc. are of type 'object', which means

typeof [] === typeof null; // is true (both are objects)
typeof [] === typeof {};   // is true (both are objects)

which is expected behaviour.

If you have to specifically check for null, arrays or other things, you could just write a better typeof function

var toType = function(obj) {
  return ({}).toString.call(obj).match(/\s([a-zA-Z]+)/)[1].toLowerCase()
}

FIDDLE

Then you could do

toType([]) === toType(['1','2','3']); // true
toType([]) === toType({});     // false
toType(1) === toType(9999);    // true
toType(null) === toType(null); // true
toType(null) === toType([]);   // false

Solution 2

If you want to distinguish object "types" from each other, it might be a good idea to compare their prototypes:

Object.getPrototypeOf([]) === Object.getPrototypeOf([1, 2, 3])
Object.getPrototypeOf({}) !== Object.getPrototypeOf([])

This will however throw if you're not passing in objects, so if you also want to compare the types of primitive values (including null) you will have to do more sophisticated tests:

function sameType(a, b) {
    var objectA = Object(a) === a,
        objectB = Object(b) === b;
    if (objectA && objectB)
        return Object.getPrototypeOf(a) === Object.getPrototypeOf(b);
    else if (!objectA && !objectB)
        return typeof a === typeof b;
    else
        return false;
}
Share:
23,624
Corey
Author by

Corey

Updated on July 09, 2022

Comments

  • Corey
    Corey almost 2 years

    What is the best way to compare two variables for identical javascript types?:

    I.E.

    [] = ['1','2','3']
    [] != {}
    Number = Number
    null = null
    

    etc. etc.