Ad

Multiple Strict Equality Comparisons In A Single Line

- 1 answer

I have the following JavaScript code:

var a = 1;
var b = 1;
a === 1        // evaluates to true
b === 1        // evaluates to true
a == b == 1    // evaluates to true
a === b === 1  // evaluates to false

Why does a === b === 1 evaluate to false?

Ad

Answer

a == b == 1

is evaluated as

((a == b) == 1)

Since a == b is true, the expression becomes

true == 1

Since == does type coercing, it converts true to a number, which becomes 1. So the expression becomes

1 == 1

That is why this expression is true. You can confirm the boolean to number conversion like this

console.log(Number(true));
// 1
console.log(Number(false));
// 0

Similarly,

a === b === 1

is evaluated as

((a === b) === 1)

so

true

so

true === 1

Since === doesn't do type coercion (as it is the strict equality operator), this expression is false.

Ad
source: stackoverflow.com
Ad