2

First up: I know this is not how one should do a comparison, this is merely a question of interest. Let's say you do this comparison:

var x = 0;
if(1 < x < 3) {
  console.log("true");
} else {
  console.log("false");
}

What is happening inside that if-statement so that the output is "true"? Is there some implicite logical comparison happening. And how do I find out?

2 Answers2

4

The comparison takes place from left to right so 1 < x < 3 will evaluate as

1 < x first which is false, given that x is 0. Here the next comparison will be,

false < 3 which will be true because there will be implicit type conversion of false to numeric representation, which is 0. So, the expression evaluates to 0 < 3 which is true.

Hence, when you do true < 3 or false < 3 then this boolean value will be implicitly converted to 0 as false and 1 as true.

Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

According to ECMAScript® 2018 Language Specification, (7.2.14) this type of comparisson is performed as follows:

7.2.14 Abstract Equality Comparison If Type(x) is the same as Type(y), then

Return the result of performing Strict Equality Comparison x === y.

If x is null and y is undefined, return true.

If x is undefined and y is null, return true.

If Type(x) is Number and Type(y) is String, return the result of the comparison x == ! ToNumber(y).

If Type(x) is String and Type(y) is Number, return the result of the comparison ! ToNumber(x) == y.

If Type(x) is Boolean, return the result of the comparison ! ToNumber(x) == y.

If Type(y) is Boolean, return the result of the comparison x == ! ToNumber(y).

If Type(x) is either String, Number, or Symbol and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).

If Type(x) is Object and Type(y) is either String, Number, or Symbol, return the result of the comparison ToPrimitive(x) == y.

Return false.

And:

7.1.3 ToNumber ( argument ): If argument is true, return 1. If argument is false, return +0.

(bolds are mine)

So:

(1 < 0 ) < 3
 false   < 3
   0     < 3
    true