== vs === and Coercion

Why loose equality is unpredictable, and the handful of cases where == is actually the right call.

Syntaxa === b x == null // null OR undefined Object.is(a, b)

Strict equality === compares value and type with no conversion. Loose equality == runs a coercion algorithm first, and that algorithm is where the famous WTF moments live.

console.log(0 == '');      // false
console.log(0 == '0');     // true
console.log('' == '0');    // false  (not transitive!)
console.log([] == ![]);    // true   ([] becomes '', ![] becomes false -> 0)

The rule that actually helps

Use === everywhere. There is exactly one useful loose comparison worth memorising: x == null is true for both null and undefined and nothing else. It is the cleanest nullish check that predates ??.

Object.is

For the two edge cases === gets philosophically wrong, use Object.is: it treats NaN as equal to itself and distinguishes +0 from -0.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Use strict equality when comparing a form field value to the string '0' so the number 0 is not treated the same.
  • Prefer === over == in all comparisons to eliminate type-coercion surprises discovered during code review.
  • Use Object.is to correctly detect NaN in a numeric validation utility.

More examples

Strict vs loose equality pitfalls

Shows how loose == performs type coercion, causing counter-intuitive results that strict === avoids.

Example Β· js
console.log(0 == false);    // true  – loose
console.log(0 === false);   // false – strict
console.log("" == false);  // true  – loose
console.log("" === false); // false – strict

Object.is for edge cases

Object.is handles the two cases where === gives surprising results: NaN identity and signed zeros.

Example Β· js
console.log(NaN === NaN);        // false – IEEE quirk
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(+0, -0));  // false
console.log(+0 === -0);          // true

Equality with type coercion algorithm

Demonstrates that null only loosely equals undefined and nothing else, a common interview question.

Example Β· js
console.log(null == undefined);   // true  – only these two
console.log(null === undefined);  // false
console.log(null == 0);          // false
console.log(null == false);      // false

Discussion

  • Be the first to comment on this lesson.
== vs === and Coercion β€” JavaScript | SoundsCode