This content originally appeared on DEV Community and was authored by Sh Raj
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.
See Video
Step-by-Step Explanation
-
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 becomesfalse
.
-
-
Now we have
[] == false
:- So now our comparison is
[] == false
. -
==
is used to check if two things are equal.
- So now our comparison is
-
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
becomes0
.
-
-
Converting
[]
to a Number:- An empty array (
[]
) becomes an empty string""
. - An empty string
""
becomes0
.
- An empty array (
-
Final Comparison:
- Now we have
0 == 0
, which istrue
.
- Now we have
Putting It All Together
- Imagine you have an empty box (
[]
). -
![]
asks, "Is this box not empty?" Since it is empty, the answer isfalse
. - When you compare the empty box to
false
, JavaScript turns both into0
. - Since
0
is equal to0
, the final result istrue
.
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.
This content originally appeared on DEV Community and was authored by Sh Raj
Sh Raj | Sciencx (2024-07-21T07:31:49+00:00) [] == ![] || Wtf JavaScript. Retrieved from https://www.scien.cx/2024/07/21/wtf-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.