Sub topic 2
Strict Equality with ===
This chapter assumes you know JavaScript's primitive types, how objects differ from primitives, and the coercion rules (ToPrimitive, ToNumber) from the previous chapter.
Strict Equality with ===
=== compares type first. If the types differ, the result is false and no conversion happens. If the types match, it compares the values. This makes === the safe default for comparisons.
Loose Equality with == and When It Coerces
== converts its operands when their types differ. null and undefined equal each other and nothing else. Objects go through ToPrimitive, booleans become numbers, and strings compared with numbers become numbers.
console.log(1 == '1'); // true
console.log(1 === '1'); // false
console.log(null == undefined); // true
console.log(null == 0); // false: special null rule
console.log(0 == ''); // true
console.log('0' == ''); // false: both strings, so no conversion
console.log([] == false); // true: [] -> '' -> 0, false -> 0The pair 0 == '' and 0 == '0' is true, but '0' == '' is false. Loose equality is not transitive.
Object.is and the SameValue Family
JavaScript uses three related algorithms:
| Algorithm | NaN equals NaN | 0 equals -0 | Used by |
|---|---|---|---|
| Strict equality | no | yes | `===`, `indexOf` |
| SameValue | yes | no | `Object.is` |
| SameValueZero | yes | yes | `includes`, `Map`, `Set` |
Edge Cases: NaN, -0, null, and undefined
console.log(NaN === NaN); // false
console.log(Object.is(NaN, NaN)); // true
console.log(Object.is(0, -0)); // false
console.log([NaN].indexOf(NaN)); // -1
console.log([NaN].includes(NaN)); // true
console.log(Number.isNaN(NaN)); // trueUse Number.isNaN to test for NaN. The global isNaN converts its argument first, so isNaN('abc') returns true.
Comparing Objects and Arrays by Reference
Objects are equal only when they are the same object in memory, so two objects with the same contents are not equal.
const a = { x: 1 };
const c = a;
console.log(a === { x: 1 }); // false
console.log(a === c); // true
console.log([1, 2] == '1,2'); // true: the array becomes '1,2'To compare contents, check each field yourself or use a deep-equality helper.
Relational Comparisons and Their Surprises
<, >, <=, and >= compare two strings by code unit and convert every other combination to numbers. They do not use the rules of ==.
console.log('10' < '9'); // true: string comparison
console.log(10 < '9'); // false: numeric
console.log(null >= 0); // true: null -> 0
console.log(null == 0); // false
console.log(undefined < 1); // false: NaNExercise
What do [NaN].includes(NaN) and [NaN].indexOf(NaN) return, and why do they differ?
Show answer
includes returns true because it uses SameValueZero, which treats NaN as equal to NaN. indexOf returns -1 because it uses strict equality, and NaN === NaN is false.
Exercise
Why is null >= 0 true while null == 0 is false?
Show answer
>= converts null to the number 0, and 0 >= 0 is true. == has a special rule: null equals only null and undefined.