1

I'm looking at Comparison operators in Javascript and came across these examples:

console.log(1 < 2 < 3);

This equals true, which feels like it makes sense as 1 is less than, 2 and 2 is less than 3...

console.log(3 > 2 > 1);

However this equals false, which I don't understand...

Here's a jsFiddle to also show the behavior if you open up the web developer tools and look at the console.

Someone suggested, it had to do with precedence but reading about precedence at MDN, I can't find a explanation to this.

Can anyone explain in a resonable simple way, what is going on there?

Ola Karlsson
  • 9,011
  • 7
  • 27
  • 37

6 Answers6

1

You are misunderstanding the way how does it works. If you write 3 > 2 > 1, the first operation is actually 3 > 2 which obviously returns true. But then it's true > 1 which returns false, because true is being changed by the math operator to 1.

In the 1 < 2 < 3 example, it returns true, because 1 < 2 returns true and true < 3 operation returns true aswell, because true is again being changed into 1 and 1 is obviously smaller than 3.

kind user
  • 40,029
  • 7
  • 67
  • 77
1

An idea

1<2<3 = (1<2)<3 = (true)<3 = (1)<3 = true

3>2>1 = (3>2)>1 = (true)>1 = (1)>1 = false

silgon
  • 6,890
  • 7
  • 46
  • 67
1

1 < 2 < 3 in javascript corresponds to ((1 < 2) < 3), that corresponds to true < 3. You're actually comparing booleans with integers, it doesn't make any sense in my opinion.

If you want to make two comparisons at once you should rewrite the condition as 3 > 2 && 2 > 1

Oneiros
  • 4,328
  • 6
  • 40
  • 69
1
console.log(1 < 2 < 3); 

evaluates as in the following way:

console.log(true < 3); is console.log(1 < 3); prints true

Then console.log(3 > 2 > 1)

evaluates as in the following way:

console.log(true > 1) is console.log(1 > 1) prints false

Mamun
  • 66,969
  • 9
  • 47
  • 59
1

In JavaScript, chaining of comparison operators won't work; it will first evaluate the first comparison to true/false, convert it into 1/0 and then do the second comparsion:

1 < 2 < 3   =>   (1 < 2) < 3
            =>      true < 3
            =>         1 < 3
            =>          true    

3 > 2 > 1   =>   (3 > 2) > 1
            =>      true > 1
            =>         1 > 1
            =>         false

You should instead split it into two separate comparsions: 1 < 2 && 2 < 3.

Frxstrem
  • 38,761
  • 9
  • 79
  • 119
0

Because of the precedence of the operation from left to right, and the fach that true is equivalent to (1)

console.log(3 > 2 > 1);
3 > 2 => true;
console.log(true > 1 );
1 > 1 => false;
true > 1 => false;
ΦXocę 웃 Пepeúpa ツ
  • 47,427
  • 17
  • 69
  • 97