3

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?

foundling
  • 1,695
  • 1
  • 16
  • 22

1 Answers1

3
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 === 1

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

Community
  • 1
  • 1
thefourtheye
  • 233,700
  • 52
  • 457
  • 497