Urgent.News

What's breaking now, across thousands of outlets.

Tech

Yes, [] == ![] Is True. No, JavaScript Isn't Broken (I Checked, Slowly).

Is JavaScript gaslighting me, or is there a logic to this? I hit this line at about 1 a.m., laptop on a pillow, one eye open. I read the result, read it again, and seriously considered that the language was making fun of me personally. This post takes that single line apart, one tiny piece at a time, until it stops being magic and starts being almost boring. That is a promise: boring is what we…

JavaScript does not appear to be broken when it returns true for the line console.log([] == ![]);. The confusion arises from understanding the logic behind the comparison. An empty array [] is considered truthy in JavaScript, so the exclamation point (!) converts it to false. Thus, the line is essentially asking if [] is equal to false.

When comparing different types (array and boolean), JavaScript quietly converts them before comparison. The boolean false converts to the number 0, and an empty array [] converts to an empty string, which in turn converts to 0. Therefore, the comparison reduces to 0 == 0, which is true.

To avoid this confusion, it is recommended to use the triple equals operator (===) instead of the double equals (==). The triple equals operator does not perform any type conversions and immediately returns false if the types are different, thus eliminating any unexpected results.

One interesting example to try is console.log(0 == false);. The boolean false converts to 0, so the comparison becomes 0 == 0, which is true. This demonstrates the importance of understanding JavaScript's type conversion rules to predict the outcome of such comparisons accurately.

Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.

Read the original at dev.to →

More in Tech

More from Saturday 7 November →