It is funny to know that there is two occasions where === returns a lying result.
The first is:
0 === -0 // True
To avoid this is useful to use Object.is()
Object.is(0, -0) // False
The second is:
NaN === NaN // false
To avoid this is useful to use isNaN()
Number.isNaN(NaN) // True
Top comments (11)
0 === -0 is true because 0 doesn't have sign
NaN === NaN is false because, according to IEEE 754 specifications any operation performed on NaN values should yield a false value or should raise an error.
-0
does in fact have a sign:en.wikipedia.org/wiki/IEEE_754
Moreover, there are two zero values, called signed zeros: the sign bit specifies whether a zero is +0 (positive zero) or −0 (negative zero).
That same Wikipedia article specifies that 0 and -0 should compare as equal.
Actually, both are valid cases, since
===
compares the actual value and not the reference. Since primitives that contain the exact same value are stored within the same reference,Object.is
will work; the value of 0 and -0 is the same, but since the sign differs, they are stored with different references.And NaN is specifically meant not to work as a number, so it should not be calculatable or comparable - so if you put garbage into JS numbers, you'll get garbage out, even if you add non-garbage numbers.
Object.is
will work again here, because the reference to both instances of NaN is still the same.So it's not a lie, even though the result might be unexpected if you are not familiar with the spec of the language.
When will you need to compare
0
and-0
, as both are just floating points?For
NaN
, well, there is nothing I can do about it...Always when you decide to use 0 and -0 in your program. I hope you never have to use -0 but it's up to you 🙂.
0.1 + 0.2 !== 0.3
is headache enough, but now just let1 - 1 === -1 + 1
, please.Why would one HAVE to use -0? -0 is flawed, since, 0 is neutral, it doesn't have a sign.
Take 1 for example, 1 == +1 since 1 has the + sign, where as with 0, is not +0 because 0 has no sign. So 0 === -0 being true is actually one of the few places where JS is right.
Hi Tomaz, I’m not talking about why ... I just show a fact 🙂 I never use -0 in my life but I am not God I am just a person.
Use or not it’s up to you 🙂
Another day, another developer discovers IEEE 754 double-precision floating-point standard.
As exhibit A I present to you
Reference: floating-point-gui.de/
Did you also get the question about what is the difference between "==" and "===" at your first JavaScript interview?