Equality and coercion in JavaScript
=== compares without converting; == converts first, and surprises.
const comparisons = [
["'1' == 1", "1" == 1],
["'1' === 1", "1" === 1],
["null == undefined", null == undefined],
["null === undefined", null === undefined],
["[] == false", [] == false],
["NaN === NaN", NaN === NaN],
["Object.is(NaN, NaN)", Object.is(NaN, NaN)],
["Object.is(0, -0)", Object.is(0, -0)],
];
for (const [expression, result] of comparisons) {
console.log(`${expression.padEnd(22)} ${result}`);
}
How it works
- Always
===unless you deliberately want the coercion. null == undefinedis true, and that is the one useful case.Object.isdiffers from===for NaN and negative zero.
Keywords and builtins used here
Objectconstforof
The run, in numbers
- Lines
- 14
- Characters to type
- 410
- Tokens
- 114
- Three-star pace
- 80 tpm
At the three-star pace of 80 tokens a minute, this run takes about 86 seconds.
Step 3 of 5 in Bindings & values, step 3 of 43 in Language basics.