Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple strict equality comparisons in a single line

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?

like image 432
foundling Avatar asked Dec 04 '25 15:12

foundling


1 Answers

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.

like image 152
thefourtheye Avatar answered Dec 06 '25 03:12

thefourtheye