21

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

console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
Boann
  • 48,794
  • 16
  • 117
  • 146
Ramesh Rajendran
  • 37,412
  • 45
  • 153
  • 234

5 Answers5

41

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
  • 510,633
  • 85
  • 743
  • 889
Zenoo
  • 12,670
  • 4
  • 45
  • 69
  • 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,216
  • 1
  • 15
  • 28
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
  • 22,460
  • 5
  • 32
  • 69
4

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,307
  • 2
  • 20
  • 34
Venom
  • 1,076
  • 1
  • 11
  • 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