Chapter IV · Operators & Expressions

Equality

The == (loose equality) operator compares two values for equality after converting them to a common type — which is exactly why it has a reputation for surprises.

01 What Is Loose Equality?

== exists from JavaScript's earliest days, when automatic type conversion was seen as a convenience: compare a string typed into a form to a number without writing the conversion yourself. In practice, its coercion rules are complicated enough that most style guides now recommend avoiding it in favor of ===.

02 Simple Example

Loose equality coercing types before comparing.

equality.js
console.log(5 == '5');   // true — string coerced to number
console.log(0 == false); // true — boolean coerced to number
console.log(null == undefined); // true — a special-cased pair
console.log('' == 0);    // true — both coerce toward 0

03 How It Works

When the operand types differ, == follows a specific conversion algorithm from the ECMAScript spec: booleans convert to numbers, numbers and strings convert toward numbers, and null/undefined are equal only to each other and to nothing else. The rules are consistent, but they're not intuitive to memorize, which is the real complaint against ==.

"5" (string) 5 (number) true (boolean) Number("5") Boolean(5) JavaScript converts between types automatically in mixed expressions — implicit coercion follows fixed rules, not guesswork.

Loose equality silently converts types before comparing them.

04 Mental Model

"A translator who insists on converting everyone to the same language before comparing what they said — helpful in theory, but the translation rules aren't always what you'd guess."

05 Common Mistakes & Best Practice

  • [] == false is true — arrays coerce to strings, then to numbers, landing on 0.
  • Best practice: default to === everywhere. The one accepted exception some style guides allow is value == null, which cleanly checks for both null and undefined in one comparison.

06 Interview Questions

Q: Is there any case where == is still considered acceptable style?

value == null is a common accepted exception — it checks for both null and undefined in a single comparison.

Q: Why is [] == false true?

Arrays coerce to a string ('' for an empty array), which then coerces to a number (0), which equals the coerced false (also 0) — two coercion steps compounding into a surprising result.

Key Takeaway

== compares after coercing operands to a common type, following spec rules that are consistent but easy to misjudge — which is why === is the default choice in modern code.

Related Concepts