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' == 1and0 == falseare bothtrue.===is strict equality: no conversion happens, so operands of different types are never equal.'1' === 1isfalse.
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.