DEV Community

Sh Raj
Sh Raj

Posted on • Originally published at sh20raj.gitbook.io

2 1 1 1 1

[] == ![] || Wtf JavaScript

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

  1. 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.
  2. Now we have [] == false:

    • So now our comparison is [] == false.
    • == is used to check if two things are equal.
  3. 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.
  4. Converting false to a Number:

    • false becomes 0.
  5. Converting [] to a Number:

    • An empty array ([]) becomes an empty string "".
    • An empty string "" becomes 0.
  6. Final Comparison:

    • Now we have 0 == 0, which is true.

Putting It All Together

  • 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.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

SurveyJS custom survey software

JavaScript UI Library for Surveys and Forms

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

View demo

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay