Sub topic 8
Loose Equality with == and When It Coerces
This chapter assumes you already know how strict equality (===) works and have met the main coercion steps: ToPrimitive, ToNumber, and ToString. You should also be comfortable running snippets in Node.js or a browser console. The goal is to replace guesswork about == with a short algorithm that you can apply by hand.
The working model
Loose equality (==, and its negation !=) does not convert both sides to one fixed type. It looks at the pair of types involved and picks a single conversion step. Then it compares again, and that second comparison may trigger another step. Each step pushes the operands toward numbers, so most == comparisons end up comparing two numbers or two strings.
The specification calls this algorithm IsLooselyEqual. With the rarely relevant browser quirk document.all left out, it works like this:
- If both operands have the same type, return the result of
===. - If one side is
nulland the other isundefined, returntrue. - If one side is a Number and the other a String, convert the String with ToNumber and compare again.
- If one side is a BigInt and the other a String, parse the String as a BigInt. If it fails to parse, return
false. - If either side is a Boolean, convert that Boolean to a Number (
trueto1,falseto0) and compare again. - If one side is an object and the other is a String, Number, BigInt, or Symbol, convert the object with ToPrimitive and compare again.
- If one side is a BigInt and the other a Number, compare their mathematical values.
NaNandInfinitynever match. - Otherwise, return
false.
Some things are missing from that list. null and undefined are never converted. Rule 2 is the only rule that mentions them, so they are loosely equal to each other and to nothing else. Booleans are never compared as booleans. They always turn into 0 or 1 first.
Tracing real comparisons
The snippet below includes the comparisons that usually confuse people. The comment on each line shows the conversion steps.
console.log(0 == ''); // true: '' -> 0, then 0 === 0
console.log(0 == '0'); // true: '0' -> 0
console.log('0' == ''); // false: both strings, so === applies
console.log(' \n42\t' == 42); // true: ToNumber trims whitespace
console.log(true == '1'); // true: true -> 1, '1' -> 1
console.log(true == 'true'); // false: true -> 1, 'true' -> NaN
console.log(null == 0); // false: null only matches null/undefined
console.log(undefined == false); // false: false -> 0, undefined == 0 is false
console.log([] == false); // true: false -> 0, [] -> '', '' -> 0
console.log([] == ![]); // true: ![] is false, then as above
console.log([0] == false); // true: [0] -> '0' -> 0
console.log({} == '[object Object]'); // true: ToPrimitive gives that string
console.log(10n == '10'); // true: '10' parsed as BigInt
console.log(1n == 1); // true: same mathematical value
console.log(Symbol() == 'x'); // false: no rule converts a Symbol hereThe first three lines show that == is not transitive. 0 == '' and 0 == '0' are both true, but '' == '0' is false. Rule 1 applies to the third comparison because both operands are strings, so no conversion happens.
Objects and ToPrimitive
When an object meets a primitive, rule 6 calls ToPrimitive with the hint "default". For plain objects and arrays, that means valueOf() is tried first. It returns the object itself, which is not a primitive, so toString() runs next. Your own objects can change the result:
const price = { valueOf() { return 42; } };
console.log(price == 42); // true: valueOf returns 42
console.log(price == '42'); // true: 42 == '42', then '42' -> 42
const d = new Date(0);
console.log(d == 0); // false: Date treats "default" as "string"
console.log(d == d.toString()); // true
console.log(new Number(5) == 5); // true: unwrapped by ToPrimitive
console.log(new Number(5) == new Number(5)); // false: two objects, compared by identityWhen both operands are objects, rule 1 applies and nothing is converted. Two distinct objects are never loosely equal, even if their contents match.
Checking the model in code
The function below implements the rules for every type except BigInt. It then compares its output with the real == operator. Running it is a quick way to check that the algorithm above explains the behavior completely.
function typeTag(v) {
if (v === null) return 'null';
const t = typeof v;
return t === 'function' ? 'object' : t;
}
function toPrimitive(obj) {
const exotic = obj[Symbol.toPrimitive];
if (typeof exotic === 'function') return exotic.call(obj, 'default');
for (const method of ['valueOf', 'toString']) {
if (typeof obj[method] === 'function') {
const result = obj[method]();
if (typeTag(result) !== 'object') return result;
}
}
throw new TypeError('Cannot convert object to primitive value');
}
const PRIMS = ['string', 'number', 'bigint', 'symbol'];
function looseEqual(x, y) {
const tx = typeTag(x);
const ty = typeTag(y);
if (tx === ty) return x === y;
if ((tx === 'null' && ty === 'undefined') || (tx === 'undefined' && ty === 'null')) return true;
if (tx === 'number' && ty === 'string') return looseEqual(x, Number(y));
if (tx === 'string' && ty === 'number') return looseEqual(Number(x), y);
if (tx === 'boolean') return looseEqual(Number(x), y);
if (ty === 'boolean') return looseEqual(x, Number(y));
if (tx === 'object' && PRIMS.includes(ty)) return looseEqual(toPrimitive(x), y);
if (ty === 'object' && PRIMS.includes(tx)) return looseEqual(x, toPrimitive(y));
return false; // BigInt-specific rules omitted
}
const cases = [
[0, ''], ['0', ''], [true, '1'], [true, 'true'], [null, 0],
[null, undefined], [undefined, false], [[], false], [[1, 2], '1,2'],
[{}, '[object Object]'], [new Date(0), 0], [NaN, NaN], [Symbol.iterator, 'x'],
];
for (const [a, b] of cases) {
const ok = looseEqual(a, b) === (a == b);
console.log(ok ? 'match' : 'MISMATCH', String(a), '==', String(b), '->', a == b);
}Every line should print match.
Common errors
| Code | What people expect | What actually happens |
|---|---|---|
| `if (x == true)` | Runs for any truthy `x` | `true` becomes `1`, so `'yes' == true` is false |
| `if (x == false)` | Runs for any falsy `x` | `undefined == false` and `null == false` are false |
| `input == 0` | Matches only zero | Also matches `''`, `' '`, `'0'`, and `[]` |
| `a == b == c` | Checks that all three match | Compares `(a == b)`, a boolean, against `c` |
| `value == NaN` | Detects `NaN` | Always false; use `Number.isNaN` |
The first two rows cause the most bugs. Comparing with == true or == false does not test truthiness. To test truthiness, use the value directly in a condition or apply Boolean(x).
Choosing between == and ===
Use === by default. Its result depends only on the two values and never on conversion rules. Use == only when you want its conversions, as with x == null, and when everyone reading the code knows the rules. If you have to compare values of different types, convert them yourself first, for example Number(input) === 0. The conversion is then visible in the code and nobody has to remember the hidden rules.
Exercise
Trace the steps for [1] == true and [2] == true. Which one is true, and why?
Show answer
Rule 5 converts true to 1 first. For [1] == 1, ToPrimitive turns [1] into '1', then '1' becomes 1, and 1 === 1 is true. For [2] == 1, the array becomes '2' and then 2, and 2 === 1 is false. So only [1] == true is true, even though both arrays are truthy.
Exercise
Why is null == 0 false while null >= 0 is true?
Show answer
Loose equality never converts null. Rule 2 is the only rule that mentions it, so null equals only null and undefined. Relational operators follow a separate algorithm that applies ToNumber to both sides, turning null into 0, and 0 >= 0 is true.
Exercise
A function receives count, which may be a number, a numeric string, or undefined. Rewrite if (count == 0) so that only the number 0 or the string '0' passes and undefined, '' and [] do not.
Show answer
Convert explicitly, then compare strictly: if (count !== undefined && count !== '' && Number(count) === 0). A narrower and clearer option is if (count === 0 || count === '0'). Both versions reject '', whitespace-only strings, and arrays, which == 0 would accept.