Equality¶
Equality in JavaScript can be a little odd.
Double equals¶
JavScript has two operations for equality (and inequality). One of them is ‘==’ (and ‘!=’ for inequality). It’s the oddest.
Not transitive¶
If a is equal to b, and if b is equal to c , then we expect a to be equal to c. This is called the transitive property.
js> '0' == 0 // 'a' is equal to 'b'
true
js> 0 == '' // 'b' is equal to 'c'
true
js> '0' == '' // 'a' is not equal to 'c'
false
Not reflexive¶
We expect a to be equal to a. This is called the reflexive property.
js> NaN == NaN
false
Fortunately, this seems to be the only example.
Is symmetric¶
If a is equal to b then we expect b to be equal to a. This is called the symmetric property. In JavaScript equality is symmetric.
Triple equality¶
JavaScript also has ‘===’ (and ‘!==’ for inequality).
Is transitive¶
Unlike double equals, triple equals is always transitive.
js> '0' === 0 // unequal
false
js> 0 === '' // unequal
false
js> '0' === '' // unequal
false
Not reflexive¶
js> NaN === NaN
false
By the way, there’s a thread on Facebook with subject Time and Date on my wall shows NaNNaNNaN at NaN:NaN. I wonder how that happened.
Is symmetric¶
Triple equality is still symmetric.
Don’t use double equality¶
Double equality does implicit conversions and besides has some odd rules. My advice is don’t use double equality.
Triple equality does not do conversions. If you want to do conversions in your comparision my advice is to make them explicit.
Compare as string¶
The easiest conversion is to string. Here are two immutables, a number and a string.
js> a = 0
0
js> b = '0'
0
These quantities are double equal but not triple equal.
js> a == b
true
js> a === b
false
Here’s how to do an explicit conversion to string before comparison, which gives an equality.
js> '' + a === '' + b // Converts variables to strings.
true
Note
It’s always easier to read a triple equal comparison, because you’re not distracted by the complex double equal rules.
Compare as number¶
[To follow later.]