18

Why does 3>2>1 return false while 1 < 2 < 3 returns true?

console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
Boann
  • 47,128
  • 13
  • 114
  • 141
Ramesh Rajendran
  • 35,211
  • 40
  • 143
  • 222

5 Answers5

37

Since 1 < 2 evaluates to true and 3 > 2 evaluates to true, you're basically doing :

console.log(true < 3);
console.log(true > 1);

And true is converted to 1, hence the results.

deceze
  • 491,798
  • 79
  • 706
  • 853
Zenoo
  • 12,242
  • 4
  • 44
  • 63
  • See also [MDN: Operator precedence](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence) for operator precedence and associativity. – feeela Aug 02 '18 at 07:41
11

Because it interprets left to right and because it tries to cast to same type.

1 < 2 < 3 becomes true < 3, which because we are comparing numbers is cast to 1 < 3 which is truth.

3 > 2 > 1 becomes true > 1, which because we are comparing numbers is cast to 1 > 1 which is false.

Emil S. Jørgensen
  • 6,020
  • 1
  • 11
  • 25
8

That is because it is evaluated from left to right, making it equivalent to the below commands:

console.log(true < 3);
console.log(true > 1);
Peter B
  • 21,067
  • 5
  • 28
  • 63
3

Operator "<" and ">" Associativity is left-to-right so

Check below link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence

console.log(1 < 2 < 3) ==> console.log(true < 3)==> (true means 1)=> console.log(1 < 3); Answer is true

console.log(3 > 2 > 1) ==> console.log(true >1)==> (true means 1)=> console.log(1 >1); Answer is false

console.log(3 > 2 >=1) ==> console.log(true >=1)==> (true means 1)=> console.log(1 = 1); Answer is true

slee423
  • 1,261
  • 2
  • 18
  • 33
Venom
  • 1,056
  • 1
  • 10
  • 23
2

Compiler will read like this $console.log((1 < 2) < 3) and $ console.log(( 3>2 ) > 1)

in 1st case: $ console.log(1 < 2 < 3) first compiler execute 1<2 which returns 1(true), after that it goes like 1<3 which is again 1(true). hence overall it is true.

execute 2nd one with same logic, it will gives you false.

Divyanshu
  • 91
  • 1
  • 3