Sub topic 7
Strict Equality with ===
Strict equality is the comparison you will use most often in JavaScript. The === operator answers one question: are these two values the same type and the same value? It never converts either operand first. That makes its results easy to predict, which is why most style guides make it the default.
This chapter assumes you know the JavaScript primitive types (number, string, boolean, null, undefined, symbol, bigint) and that objects are separate from primitives. It also assumes you have read the earlier chapter on type coercion, because the main thing === does is skip coercion.
What === Actually Checks
The specification calls this algorithm IsStrictlyEqual. It works in two stages.
- If the two operands have different types, the result is
false. No conversion happens. - If they have the same type, the comparison depends on that type.
| Type | Rule for `x === y` when both share this type |
|---|---|
| Undefined | Always `true` |
| Null | Always `true` |
| Boolean | `true` if both are `true` or both are `false` |
| String | `true` if both have the same sequence of UTF-16 code units |
| Number | `true` if numerically equal; `NaN` is never equal to anything; `0` and `-0` are equal |
| BigInt | `true` if mathematically equal |
| Symbol | `true` only if both are the same symbol |
| Object | `true` only if both refer to the same object |
The Number row has two exceptions, NaN and -0. The Object row compares identity, not contents. Later chapters cover each of these in depth. For now, just remember that they exist.
Strict Equality in Practice
Run this in Node.js or a browser console:
console.log(1 === 1); // true
console.log(1 === '1'); // false: number vs string
console.log(true === 1); // false: boolean vs number
console.log(null === undefined); // false: different types
console.log(undefined === undefined); // true
console.log('abc' === 'abc'); // true: same code units
console.log(10n === 10n); // true
console.log(10n === 10); // false: bigint vs number
const id = Symbol('id');
console.log(id === id); // true
console.log(Symbol('id') === Symbol('id')); // false: two distinct symbols
console.log(Symbol.for('id') === Symbol.for('id')); // true: same registry symbol
const box = { v: 1 };
console.log(box === box); // true: same object
console.log({ v: 1 } === { v: 1 }); // false: two different objectsThe !== operator is the exact negation of ===. x !== y always gives the opposite result of x === y, with no extra rules.
console.log(1 !== '1'); // true
console.log(NaN !== NaN); // true, because NaN === NaN is falseCommon Errors
Comparing raw input without converting it
Form fields, URL parameters, process.argv, and localStorage all give you strings. If you compare one of these directly to a number, the check always fails, and nothing reports an error.
const input = '5'; // for example, from an <input> element
console.log(input === 5); // false
console.log(Number(input) === 5); // true: convert explicitly, then compareConverting explicitly is better than switching to ==. The conversion shows up in your code where readers can see it, and you can check its result with Number.isNaN before you rely on it.
Floating-point results
=== compares the exact binary value of a number. Decimal fractions often cannot be stored exactly in binary.
console.log(0.1 + 0.2 === 0.3); // false
console.log(0.1 + 0.2); // 0.30000000000000004
function nearlyEqual(a, b, tolerance = Number.EPSILON) {
return Math.abs(a - b) < tolerance;
}
console.log(nearlyEqual(0.1 + 0.2, 0.3)); // trueNumber.EPSILON works as a tolerance for values close to 1. For larger values, or for values that come out of long calculations, choose a tolerance that fits your domain. For money, store whole cents as integers.
Strings that look identical but are not
Strings compare by UTF-16 code units, not by how they look on screen. An accented letter can be written as one precomposed character or as a base letter followed by a combining mark.
const composed = 'caf\u00e9'; // é as one code point
const decomposed = 'cafe\u0301'; // e + combining acute accent
console.log(composed === decomposed); // false
console.log(composed.length, decomposed.length); // 4 5
console.log(composed.normalize('NFC') === decomposed.normalize('NFC')); // trueIf you compare text from users, files, or other systems, normalize it before comparing.
Primitive wrapper objects
new String, new Number, and new Boolean create objects, not primitives. An object is never strictly equal to a primitive.
const wrapped = new String('a');
console.log(typeof wrapped); // 'object'
console.log(wrapped === 'a'); // false
console.log(String(wrapped) === 'a'); // true: String() without new returns a primitiveCalling String(), Number(), or Boolean() without new is fine, because those calls return primitives. Avoid the new forms.
Expecting content comparison for objects and arrays
[1, 2] === [1, 2] is false because each literal creates a new array. The chapter on reference equality explains how to compare contents.
Where JavaScript Uses Strict Equality for You
Some built-in features use strict equality without showing a === sign:
switchmatches eachcaseusing strict equality.Array.prototype.indexOfandlastIndexOfuse strict equality, so[NaN].indexOf(NaN)is-1.
The switch behavior catches people who pass in string input:
function label(code) {
switch (code) {
case 1:
return 'one';
case 2:
return 'two';
default:
return 'unknown';
}
}
console.log(label(1)); // 'one'
console.log(label('1')); // 'unknown': '1' === 1 is falseArray.prototype.includes, Map, and Set use a different algorithm called SameValueZero, which treats NaN as equal to itself. The chapter on Object.is and the SameValue family covers it.
Why === Is the Default Choice
There are practical reasons for this default:
- The result depends only on the type and value of each operand, so you never need to work through a conversion table in your head.
===is transitive for every value exceptNaN. Ifa === bandb === c, thena === c. Loose equality is not transitive.- Type mismatches show up as a clear
false, so you see them early and fix them with an explicit conversion.
Exercise
Predict each result: (a) '' === 0, (b) null === null, (c) 2n === 2, (d) new Number(3) === 3, (e) NaN !== NaN.
Show answer
(a) false, because string and number are different types. (b) true, because both operands are null. (c) false, because bigint and number are different types. (d) false, because new Number(3) is an object and 3 is a primitive. (e) true, because NaN === NaN is false and !== negates it.
Exercise
A function reads a page number from a query string and runs if (page === 1) showIntro();. The intro never appears, even for ?page=1. Explain why and fix the check without using ==.
Show answer
Query-string values are strings, so page holds '1'. The types differ, so '1' === 1 is false. Convert explicitly: const pageNum = Number(page); if (pageNum === 1) showIntro();. You can also check Number.isNaN(pageNum) to reject input that is not a number.
Exercise
Why does 0.1 + 0.2 === 0.3 return false, and how would you compare two prices in a shopping cart reliably?
Show answer
0.1 and 0.2 cannot be stored exactly in binary floating point, so their sum is 0.30000000000000004, which is a different number from 0.3. For prices, store whole cents as integers (for example 30 instead of 0.30) and compare those with ===. For general floating-point values, compare with a tolerance: Math.abs(a - b) < tolerance.