Javascript Fundamentals · Interview Fundamentals

Equality in JavaScript

==, ===, Object.is, and NaN

Equality in JavaScript

1 == '1'; // true  (string coerced to number)
1 === '1'; // false (different types)
null == undefined; // true
null === undefined; // false

Two values that look nothing alike come out equal with one operator and unequal with the other. JavaScript has two equality operators, and they disagree about coercion.

  • == is loose equality: if the operands have different types, it converts one to the other before comparing. That is why '1' == 1 and 0 == false are both true.
  • === is strict equality: no conversion happens, so operands of different types are never equal. '1' === 1 is false.

Strict equality is the default you should reach for. Its one surprise is NaN, the "not a number" value: NaN === NaN is false, because a value that is not a number is never considered equal to itself.

When you need to treat NaN as equal to NaN — and to tell +0 apart from -0 — use Object.is. It behaves like === except for those two cases:

Object.is(NaN, NaN); // true
Object.is(0, -0); // false

A common interview trap is comparing objects: === checks reference identity, so two structurally identical objects are not equal unless they are the same object.

You are about to answer a short quiz on equality.

  1. `===` converts the operands to the same type before comparing them.
  2. The ___ equality operator performs type coercion when the operands differ in type.
  3. `NaN === NaN` evaluates to `false`.
  4. To treat `NaN` as equal to itself, use ___.
  5. `null == undefined` is `true`, but `null === undefined` is `false`.
  6. `Object.is(0, -0)` evaluates to ___.
  7. `===` compares two structurally identical objects as equal.