MEPX
Chapter 5 of 16All chapters

Chapter 5 of 16

Comparison and coercion

Why 0 == "0" is true and === is safer.

Two operators

The == operator converts both sides to a common type before comparing, so 0 == "0" is true. The === operator compares type and value, so 0 === "0" is false.

  • Reach for === by default and use == only when you want the conversion.
  • NaN is never equal to anything, including itself. Number.isNaN is the test.

Truthy and falsy

Only eight values are falsy: false, 0, -0, 0n, the empty string, null, undefined and NaN. Everything else is truthy, including "0", [] and {}, which catches people checking for empty lists.