Reputation: 845
What is the best way to compare two variables for identical javascript types?:
I.E.
[] = ['1','2','3']
[] != {}
Number = Number
null = null
etc. etc.
Upvotes: 12
Views: 42741
Reputation: 318212
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()
}
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
Upvotes: 21
Reputation: 8192
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)
);
}
Upvotes: 0
Reputation: 840
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
typeof 5 === typeof 37
typeof {} === typeof []
Upvotes: 0
Reputation: 664548
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;
}
Upvotes: 5