[] == ![]
Last updated
Last updated
JavaScript, the ubiquitous language of the web, is known for its quirks and peculiarities. One such enigma that often baffles both novice and experienced developers is the expression [] == ![]. This seemingly simple comparison results in true, leading many to exclaim, "WTF, JavaScript?!". Let's dive into the mechanics behind this puzzling behavior and uncover the logic (or lack thereof) that drives it.
Starting with ![]
:
[]
is an empty array.
When you put !
(which means "not") in front of something, it turns it into its opposite.
An empty array is kind of like saying "something exists" (so it's like true
).
![]
means "not an empty array," which is like saying "not true," so it becomes false
.
Now we have [] == false
:
So now our comparison is [] == false
.
==
is used to check if two things are equal.
Type Coercion:
JavaScript tries to make different things look the same when comparing them. This is called "type coercion."
When comparing an array ([]
) and a boolean (false
), JavaScript converts both to numbers.
Converting false
to a Number:
false
becomes 0
.
Converting []
to a Number:
An empty array ([]
) becomes an empty string ""
.
An empty string ""
becomes 0
.
Final Comparison:
Now we have 0 == 0
, which is true
.
Imagine you have an empty box ([]
).
![]
asks, "Is this box not empty?" Since it is empty, the answer is false
.
When you compare the empty box to false
, JavaScript turns both into 0
.
Since 0
is equal to 0
, the final result is true
.
So, [] == ![]
is true
because JavaScript does some magic behind the scenes to turn the empty box and false
into the same thing (both 0
), and then says they are equal.