DEV Community

Eugene Karataev
Eugene Karataev

Posted on

My favorite type coercion example

[] == ![] // true
Enter fullscreen mode Exit fullscreen mode

How is an empty array equal to a not empty array?! It doesn't make sense!
That's the reason why there are a lot of articles and videos on wtfjs theme.

Most developers prefer not to use double equals at all to avoid such issues.
IDE code checker may warn you not to use ==.
IDE warn

And this is a good decision to always use ===.

But I really like Kyle Simpson's YDKJS series and his why attitude. Why does JS behave like that? Let's dive in deeper!

== operator allows types coercion. It means that if two compared values are of different types, JS will try to coerce them to the same type before comparison.

What's the coercion algorithm? Actually it's pretty straightforward and defined in ECMAScript language specification.

It might look scary at first, so let's follow this algorithm step by step using the example from the beginning of the post.

[] == ![] - expression statement of our interest
First of all, before the actual comparision JS engine will execute all operands.

Step 1
[] == false
The right operand is the boolean type, so the result of comparision [] == ToNumber(false) is returned.

Step 2
[] == 0
[] is the object and 0 is the number, ToPrimitive([]) == 0 is returned.

Step 3
"" == 0
"" is the string and 0 is the number, ToNumber(x) == y is returned.

Step 4
0 == 0
true is returned.

It's fascinating how much work a JS engine does under the hood. But it follows the clear algorithm, no magic involved.
Read the specification, learn how JS works, be a better developer πŸ˜‰

P.S. I really love this tool which decomposes any JS comparison expression according to the ECMAScript language specification.

Top comments (1)

smz_68 profile image

i can good remember when i wanted to get new job they ask me things and i could not be able to Answer it