Question

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

I.E.

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

etc. etc.

Was it helpful?

Solution

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

OTHER TIPS

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;
}

This should work for all "types":

function haveSameType(a,b) {
  return (a instanceof Array && b instanceof Array) ||
    (a === null && b === null) ||
    (typeof a === typeof b && 
     b !== null && 
     a !== null &&
     ! (a instanceof Array) &&
     ! (b instanceof Array)
    );
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top