Nothing can be simpler than comparing two numbers. However, there are some details that you need to know about comparing numbers in JS.
So, what happens under the hood when you write x === y
and both x
and y
are numbers?
- If
x
isNaN
, returnfalse
- If
y
isNaN
, returnfalse
- If
x
has the same value asy
, returntrue
- If
x
is0
and y isβ0
, returntrue
- If x is
β0
and y is0
, returntrue
- Else return false
2 interesting facts that you can take away from this if
chain are:
- If both numbers are
NaN
, the result isfalse
. Should it betrue
instead? - If the numbers are
0
and-0
, the result istrue
. Should it befalse
instead?
You can have your own opinion on how something should work, but that’s how things are in JavaScript world.
Sometimes you log two values to the console, they seem equal, yet when you compare them, the result is false. And sometimes it’s the other way around.