-1

As we know about the greater than and less than operator that how they work.

    console.log(2 < 12) // true
    
    console.log(2 < "12") // true

    console.log("2" > "12") // true

But when we compare more than 2 values with greater than and less than operator. Then I can't understand the logic behind the scene.

    1. console.log(1 > 2 < 3) // true      and     console.log(1 > 2 > 3) // false

    2. console.log(9 > 2 > 9 < 8 < 9) // true
    
    3. console.log(9 > 8 > 7 > 9 > 5) // false

Can somebody please elaborate and explain behind the reason for 1 , 2 and 3 ?

  • You can only do comparisons between two values. Split the out and use the AND (&&) or the OR (||) operators – evolutionxbox Apr 11 '21 at 11:03
  • @evolutionxbox thank you for your response and I understand your point but in log why I'm getting true for 2 and false for 3 ? That is the confusion . – BHUPENDRA SINGH Apr 11 '21 at 11:06
  • it evaluates beginning from left to right, 1>2 is false which is zero and zero is less than 3 which gives true for the console.log(1 > 2 < 3) example – MWO Apr 11 '21 at 11:06
  • The last evaluation of `2.` is `true < 9` for `3.` it’s `false > 5`. – t.niese Apr 11 '21 at 11:10
  • Thanks @charly1212 I got your point with the below logic. Correct me if I'm wrong . 9 > 2 = 1 > 9 = 0 < 8 = 1 < 9 for 1 9 > 8 = 1 > 7 = 0 > 9 = 0 > 5 for 2 – BHUPENDRA SINGH Apr 11 '21 at 11:10
  • There's no operator for "comparing more than 2 values" in JS (and in many other languages). That's several separate compares between result of previous compare and next number. – Oleg V. Volkov Apr 11 '21 at 11:39

1 Answers1

1

I'd like to clear this problem using following example.

1 < 2 < 3 // evaluates to true

But

3 > 2 > 1 // evaluates to false

As we know js execute from left to right. Therefor, in first example when statement

1 < 2 

is executed it evalutes to true. In programming true refers to 1 and false refers to zero. Then after executing the above statement we have true means 1. Now when this result is combined with next statement

true < 3 

Then in short this statement means

1 < 3 

because true refers to 1 in programming. Since 1 < 3 is true that's why we have the final result as true.

Coming to the next example 3 > 2 > 1 which evaluates to false because

3 > 2 // evaluates to true 

Since above statement is true then in programming sense we got 1(true) and then by combining this result with next statement

true > 1 // evaluates  to false

The above statement is in short

1 > 1 

Since 1 is not greater than 1 therefor it returns the final result to false.

3 > 2 = true
true > 1 = false

So finally we conclude that by programming sense both statement evaluates to different results but in sense of mathematics both are same. Its a interview question. Hopefully you understand this.

Please let me know if needs any other information. In other case, It might be accepted answer.

Muhammad Atif Akram
  • 1,204
  • 1
  • 4
  • 12