Sub topic 15
Inside Loose Equality (==)
This chapter assumes you have read the earlier chapters on strict equality, ToNumber, ToBoolean, and ToPrimitive. Here you will learn the exact algorithm behind ==. The specification calls it IsLooselyEqual. Once you know its steps, results like [] == ![] stop looking random. You can trace each one in a few moves.
The Working Model
Loose equality never converts both operands to one shared type in a single jump. It repeats a cycle instead. It looks at the two types, applies one conversion to one side, and runs the comparison again. Each pass makes the types more alike. Once both operands have the same type, it hands them to strict equality (===).
Some facts shape everything else:
- If the types already match,
==behaves exactly like===. That is whyNaN == NaNisfalseand[] == []isfalse. nullandundefinedequal each other and nothing else. They are never converted to numbers.- Booleans are always converted to numbers first. ToBoolean is never applied to an operand.
- Objects go through ToPrimitive with the
"default"hint, but only when the other side is a primitive.
The Algorithm Step by Step
Here are the steps of IsLooselyEqual(x, y), in order:
| Step | Condition | Action |
|---|---|---|
| 1 | Same type | Return `x === y` |
| 2 | One is `null`, the other `undefined` | Return `true` |
| 3 | Number and String | Convert the string with ToNumber, compare again |
| 4 | BigInt and String | Convert the string with StringToBigInt. If that fails, return `false`. Otherwise compare again |
| 5 | Either is Boolean | Convert the boolean with ToNumber, compare again |
| 6 | Object and String, Number, BigInt, or Symbol | Apply ToPrimitive to the object, compare again |
| 7 | BigInt and Number | Return `false` if the number is NaN or ±Infinity. Otherwise compare the mathematical values |
| 8 | Anything else | Return `false` |
Building a Tracer
The best way to absorb these rules is to write them out as code. The function below follows the specification's steps. It records each step it takes and checks its answer against the real == operator. Run it in Node.js or a browser console.
function typeOf(v) {
if (v === null) return "null";
const t = typeof v;
return t === "function" ? "object" : t;
}
function show(v) {
const t = typeOf(v);
if (t === "string") return JSON.stringify(v);
if (t === "bigint") return `${v}n`;
if (t === "symbol") return v.toString();
if (t === "object") {
if (Array.isArray(v)) return `[${v.map(show).join(", ")}]`;
if (v instanceof Date) return "Date";
return "{}";
}
return Object.is(v, -0) ? "-0" : String(v);
}
function toPrimitiveDefault(obj) {
const exotic = obj[Symbol.toPrimitive];
if (exotic !== undefined && exotic !== null) {
const result = exotic.call(obj, "default");
if (typeOf(result) !== "object") return result;
throw new TypeError("Cannot convert object to primitive value");
}
for (const name of ["valueOf", "toString"]) {
const method = obj[name];
if (typeof method === "function") {
const result = method.call(obj);
if (typeOf(result) !== "object") return result;
}
}
throw new TypeError("Cannot convert object to primitive value");
}
function looseEquals(x, y, trace = []) {
trace.push(`${show(x)} == ${show(y)}`);
const tx = typeOf(x);
const ty = typeOf(y);
const primitives = ["string", "number", "bigint", "symbol"];
if (tx === ty) return x === y;
if ((tx === "null" && ty === "undefined") || (tx === "undefined" && ty === "null")) return true;
if (tx === "number" && ty === "string") return looseEquals(x, Number(y), trace);
if (tx === "string" && ty === "number") return looseEquals(Number(x), y, trace);
if (tx === "bigint" && ty === "string") {
let n;
try { n = BigInt(y); } catch { return false; }
return looseEquals(x, n, trace);
}
if (tx === "string" && ty === "bigint") return looseEquals(y, x, trace);
if (tx === "boolean") return looseEquals(Number(x), y, trace);
if (ty === "boolean") return looseEquals(x, Number(y), trace);
if (primitives.includes(tx) && ty === "object") return looseEquals(x, toPrimitiveDefault(y), trace);
if (tx === "object" && primitives.includes(ty)) return looseEquals(toPrimitiveDefault(x), y, trace);
if ((tx === "bigint" && ty === "number") || (tx === "number" && ty === "bigint")) {
const num = tx === "number" ? x : y;
const big = tx === "bigint" ? x : y;
if (!Number.isInteger(num)) return false;
return BigInt(num) === big;
}
return false;
}
const cases = [
[null, undefined], [null, 0], [undefined, 0], ["", 0], ["0", false],
["2", true], [[1], 1], [[], false], [[], ![]], [NaN, NaN],
[10n, "10"], ["1.5", 1n], [1n, 1], [new Date(0), new Date(0).toString()],
[{}, "[object Object]"], [[], []]
];
for (const [x, y] of cases) {
const trace = [];
const result = looseEquals(x, y, trace);
const actual = x == y;
console.log(`${trace.join(" -> ")} => ${result}${result === actual ? "" : " MISMATCH"}`);
}No line should print MISMATCH. Each line shows the chain of rewrites == performed before it reached an answer.
Tracing the Classic Surprises
[] == ![]
The ! runs first. ![] applies ToBoolean to the array, which gives true because every object is truthy. The ! flips that to false. That leaves [] == false:
- A boolean is present, so
falsebecomes0. The comparison is now[] == 0. - An object meets a number, so ToPrimitive runs on
[].valueOfreturns the array itself, which is not a primitive, sotoStringruns and returns"". The comparison is now"" == 0. - A string meets a number, so
""becomes0. The comparison is now0 == 0, which istrue.
The array was never asked whether it was truthy. Only the ! operator did that.
"2" == true
This returns false, even though if ("2") takes the branch. The boolean rule turns true into 1, and then "2" becomes 2, and 2 is not 1. This means x == true is not the same test as "x is truthy". Never write it that way.
null == 0
This returns false. No step converts null to a number. null matches only step 2, and when the other side is 0, nothing matches, so step 8 returns false. The relational operators follow different rules, which is why null >= 0 is true. A later chapter covers that.
Dates and the default hint
For most objects, the "default" hint behaves like "number". Date is the exception. Its Symbol.toPrimitive treats "default" as "string". That is why new Date(0) == new Date(0).toString() is true, while comparing the date to its timestamp number with == is false.
The One Idiom Worth Keeping
Step 2 gives a compact and safe check for "missing":
function describe(value) {
return value == null ? "missing" : `present: ${value}`;
}
console.log(describe(null)); // "missing"
console.log(describe(undefined)); // "missing"
console.log(describe(0)); // "present: 0"
console.log(describe("")); // "present: "value == null is exactly value === null || value === undefined. It does not catch 0, "", or false, because null never converts. Many style guides allow this one use of == and ban every other.
Common Errors
| Mistake | Why it fails | Use instead |
|---|---|---|
| `if (x == true)` | `"2" == true` is `false` | `if (x)` or `x === true` |
| `if (input == 0)` to detect empty input | `"" == 0` and `" " == 0` are `true` | `input.trim() === ""` |
| `arr == otherArr` to compare contents | Objects compare by identity | Compare element by element |
| `x == NaN` | `NaN` never equals anything | `Number.isNaN(x)` |
Exercise
Trace [0] == false through the loose equality algorithm and give the result.
Show answer
A boolean is present, so false becomes 0, giving [0] == 0. An object meets a number, so ToPrimitive runs on [0]: valueOf returns the array, then toString returns "0", giving "0" == 0. The string becomes 0, giving 0 == 0, which is true. The same array is truthy in an if statement, so == and truthiness disagree here.
Exercise
Why is undefined == 0 false while undefined == null is true? Name the step that decides each result.
Show answer
undefined == null matches step 2, the special null/undefined rule, and returns true. undefined == 0 matches no conversion step, because undefined is never converted by ==. It falls through to step 8 and returns false.
Exercise
Predict 1n == "1", 1n == "1.0", and 2n == 2.5.
Show answer
1n == "1" is true: StringToBigInt("1") gives 1n. 1n == "1.0" is false: "1.0" is not a valid BigInt string, so the comparison returns false. 2n == 2.5 is false: their mathematical values differ, and a non-integer Number can never equal a BigInt.