What is the best way to compare two variables for identical javascript types?:
I.E.
[] = ['1','2','3']
[] != {}
Number = Number
null = null
etc. etc.
The strict equality operator ( === ) behaves identically to the abstract equality operator ( == ) except no type conversion is done, and the types must be the same to be considered equal. The == operator will compare for equality after doing any necessary type conversions.
Use === if you want to compare couple of things in JavaScript, it's called strict equality, it means this will return true if only both type and value are the same, so there wouldn't be any unwanted type correction for you, if you using == , you basically don't care about the type and in many cases you could face ...
The strict equality operator ( === ) checks whether its two operands are equal, returning a Boolean result. Unlike the equality operator, the strict equality operator always considers operands of different types to be different.
In JavaScript, strings can be compared based on their “value”, “characters case”, “length”, or “alphabetically” order: To compare strings based on their values and characters case, use the “Strict Equality Operator (===)”.
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
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With