u/ITower__Education

A beginner-friendly breakdown of why [] == 0 is true in JavaScript (and when to use === instead)

A beginner-friendly breakdown of why [] == 0 is true in JavaScript (and when to use === instead)

I made a short lesson on JavaScript comparisons and wanted to share the main points here in case it helps anyone who is learning.

The one that surprises most beginners is that an empty form field can pass validation. "" == 0 is true, so if (quantity == 0) treats "nothing typed" as "zero items".

0 == false       // true
"" == 0          // true
[] == 0          // true
NaN === NaN      // false
"10" < "9"       // true (strings compare character by character)

The reason is that == converts the types before comparing, while === does not.

5 == "5"    // true
5 === "5"   // false

My rule for beginners is to use === by default. The one exception I use on purpose is x == null, which is true for both null and undefined.

The video goes through all of this with runnable examples, including null and undefined, the form field bug, string comparison and localeCompare.

https://youtu.be/iJJ1lJIM81A?si=LHW-Pa2Nu2ZCs969

I would be happy to answer questions if anything is unclear.

u/ITower__Education — 5 days ago