This is another one in the occasional series of, “weird JavaScript” where I address weird stuff in JavaScript that only haunts your nightmares if you dream in other programming languages.
Today we discuss what the hell ===
actually does. Buckle-up buttercups. Grab a snickers and a whisky we’re going for a ride.
== is not
- a “comparison of value, ignoring type”
- a comparison, “for values equal to each other
- “equal values”
== is:
- A conversion of the operands,
- if they are not the same type,
- and then a comparison of their values
If ==
meant “ignore type” …
Open up your browser console. Look at what happens with the following commands:
“true” == true; null == "null"; "NaN" == NaN;
If JavaScript just compared type or ignored type, then the above statements would all return true
.
But they don’t.
They all return false
.
if ==
meant, “same value”
[1] == 1; //true
Same values! they’re basically twinsies! One is just trapped inside of brackets!
[1] == true; //true
Right. I mean, that’s .. uh … huh…. [binary] or something. You know.. .1’s and 0’s and 1 means on or true
or whatever. So… yeah. it’s kinda the same value…. sort of. They’re like cousins or something.
[true] == true; // false
Well, I mean. Arrays man. Come on…who compares an array? They’re like fraternal twins or something. You can’t do that.
"true" == true; // false
Wat ‽
If JavaScript coerces type…
0 == ""; // true
The right-hand operand is coerced into a number, via Number(‘’)
. That operation produces a zero. So 0 == 0;
and that is a truth.
"0" == 0; // true
The right hand is coerced into a string via toString()
. That produces a 100% truth that “0” == “0”;
[true] == true ; // false
The left hand is coerced into a string via .toString()
. Then the right hand is coerced into a number via Number()
. Then right hand is coerced again, to a string with .toString()
. So you end up with the fake-news that “true” == “1”;
"true" == 1 ; // false
The right hand is coerced into a string via .toString()
. So you end up with the sad state of affairs that is “true” == “1”;
JavaScript has coercion rules
Those coercion rules are the key to all of this. That’s why [1] == 1
is true
, but [true] == true
is false
.
- Arrays coerce to strings,
- but booleans coerce to numbers,
- and then Numbers coerce to strings.
Get to the point, Frank. What about ===
That turns off type coercion. All of the rules about how one thing evolves into another go the way of the dodo.
That is the only way to think of ===; it does not use any coercion.
Remember
- == Values must be at least fraternal twins
- === Values must be identical twins
- != Value are frenemies
- !== values are like Mother Russia and the US