One of the most "strange" behaviors of javascript is how the ==
equality operator works. You can see pieces of code like this:
42 == '42' // true
On the internet, you'll find one common explanation about this, and is that ==
operator compares only the value in both sides of the equality without looking the type
. This is a correct explanation but is not very accurate.
One more accurate explanation is that ==
reduces both sides of the equality to their number representation
and there, it makes the comparison. Consider the following:
0 == false // true
Zero is already a number, but what happens with false
?
If you convert false
to a number you'll get this
Number(false) // 0
Then, the final comparison will be this
0 == 0 // true
Having this in mind, check this out:
[] == ![] // true
The comparison above, follows the same rule that I've mentioned before. the empty array []
if is converted to a number, gives as result:
Number([]) // 0
On the other side of the comparison, we have ![]
as we have the !
operator, this one changes the boolean value of the empty array. The boolean representation of []
is:
Boolean([]) // true
And as we have the !
operator the result is false
, and as we saw above, the number representation of false
is 0
.
As final comparison we are going to have:
0 == 0 // true
I really hope that this blog post help you to understand this behavior of javascript, the feedback is welcome and if you like this content I would be very happy if you share it.
Thanks for reading.
Top comments (0)