typestar

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

  1. Always === unless you deliberately want the coercion.
  2. null == undefined is true, and that is the one useful case.
  3. Object.is differs from === for NaN and negative zero.

Keywords and builtins used here

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.

Type this snippet

Step 3 of 5 in Bindings & values, step 3 of 43 in Language basics.

← Previous Next →