Sub topic 8
Loose Equality with == and When It Coerces
This chapter assumes you already know how strict equality (===) works and how JavaScript's conversion steps work: ToPrimitive, ToNumber, and ToString. Loose equality (==) uses those conversions. Before it compares two values, it may change one or both of them, so it follows a fixed algorithm rather than a direct type check.
The algorithm, step by step
The specification calls this algorithm IsLooselyEqual. It runs through a short list of rules and stops at the first one that applies. Some rules convert one operand and then run the comparison again with the new value.
- If both operands have the same type, compare them with
===. - If one is
nulland the other isundefined, the result istrue. - If one is a Number and the other is a String, convert the String to a Number.
- If either operand is a Boolean, convert it to a Number (
true→ 1,false→ 0). - If one is an object and the other is a primitive, convert the object with ToPrimitive.
- If one is a BigInt and the other is a Number, compare their mathematical values.
- Otherwise, the result is
false.
Tracing real examples
console.log(1 == '1'); // true: '1' becomes 1
console.log(1 === '1'); // false
console.log(null == undefined); // true: special rule
console.log(null === undefined); // false
console.log(0 == ''); // true: '' becomes 0
console.log('0' == ''); // false: both strings, compared directly
console.log(null == 0); // false: null only loosely equals undefined
console.log([] == false); // true[] == false takes three steps. The Boolean false becomes 0. Then the array goes through ToPrimitive and becomes ''. Finally '' becomes 0, and 0 == 0 is true.
Common errors
Loose equality is not transitive. In the example above, 0 == '' and 0 == '0' are both true, yet '' == '0' is false. You cannot chain == results the way you would with mathematical equality.
Comparing against booleans is another common mistake. x == true does not test whether x is truthy. It converts true to 1 and compares x against 1. That is why '2' == true is false.
null is not converted to a number by ==. This is unlike the relational operators, so null == 0 is false even though null >= 0 is true.
Exercise
Walk through the steps for '1' == [1] and 'true' == true. What does each return?
Show answer
'1' == [1]: the array goes through ToPrimitive and becomes '1'. Both operands are now strings, so the result is true. 'true' == true: the Boolean becomes 1, then 'true' becomes NaN. NaN == 1 is false.
Exercise
Why does x == null catch exactly null and undefined, while 0 == null is false?
Show answer
The algorithm has a rule that makes null and undefined loosely equal to each other. No rule converts null or undefined to a number, so comparing either one with any other value falls through to the final step and returns false.