Skip to content
Equality: == vs === and Type Coercion
step 1/7

Reading — step 1 of 7

Learn

~3 min readModern Syntax

JavaScript's loose equality (==) coerces types — and the rules are infamous. Strict equality (===) does not. Always use === unless you have a deliberate reason for the looser one. This lesson explains why.

Strict equality (===) — the safe default

No type coercion. Same type AND same value:

javascript

Loose equality (==) — coerces

With type coercion:

javascript

The full rules are a maze. Don't memorize them — just use ===.

Special case: null == undefined

The ONE exception where loose equality is widely used:

javascript

Shorter than x === null || x === undefined. Some teams allow this; others enforce strict equality everywhere.

Type coercion: the bigger picture

Loose equality is one place coercion happens. Others:

The + operator:

javascript

Comparison operators (<, >, <=, >=) — coerce to numbers (or strings if both are strings):

javascript

Boolean contexts (if, &&, ||, !):

javascript

The falsy values: false, 0 (and -0), '', null, undefined, NaN. Everything else is truthy.

Object.is — even stricter than ===

javascript

Useful when you specifically need NaN === NaN behavior (e.g., comparing values stored in a Map).

Common mistakes

  • Using == instead of ===0 == '' is true; almost never what you want.
  • Forgetting empty arrays/objects are truthyif (arr) doesn't check emptiness; check arr.length.
  • Coercion in + with mixed types'1' + 2 === '12' but '1' - 2 === -1. + is overloaded; - always coerces to number.
  • Comparing NaN with === — always false. Use Number.isNaN(x).
  • Implicit coercion in ifif (count != null && count > 0) is the safer guard than if (count).
  • Loose null check: x == null is the rare legitimate use of ==. Some style guides ban even this.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…