0

These are my variables.

value1= 15.8
value2 = 15.5
value3 = 15.3

My condition is, value1 should be greater than value2 and value2 should be greater than value3.

yes, I can achieve this through console.log( (value1 > value2) && (value2 > value3));

I tried, console.log( (value1 > value2 > value3)); It looks like fine for me, but it returns false. I want to know whether I can compare three or more variables like this, if yes what I missed here.

Thank you.

5
  • 4
    No, it's not possible. The comparison operators are binary - they only operate with two values at a time. You can only make a series of binary comparisons. Commented Dec 13, 2019 at 8:42
  • it's not possible Commented Dec 13, 2019 at 8:43
  • there´s only left- and right-hand to js-equation Commented Dec 13, 2019 at 8:45
  • value > value2 > value3 will parse as true > value3 which forces true to be evaluated as a number giving you 1 > value3 which is false Commented Dec 13, 2019 at 8:45
  • Dupe Commented Dec 13, 2019 at 8:58

2 Answers 2

1

whether I can compare three or more variables like this

Simple answer, No.

When you do

value1 > value2 > value3,

its will be parsed from left to right and will look like (value1 > value2) > value3

  1. value1 > value2: This will yield boolean value, say true
  2. true > value3: This will always yield false, unless value3 is less than 1 as rightly suggested by slebetman

When values are compared, JS will try to bring them to same type. So boolean value will be converted to numeric value.

  • true -> 1
  • false -> 0
Sign up to request clarification or add additional context in comments.

1 Comment

value3 does not need to be zero. Just less than 1. true > 0.9 is true and true > -100 is also true. This is because new Number(true) gives you 1
1

I tried, console.log( (value1 > value2 > value3)); It looks like fine for me, but it returns false.

okay consider how it's evaluated first value1 >value2 is compared which is true,

after that true > value3 is compared which is false.

I want to know whether I can compare three or more variables like this

in this case it will be evaluated from left to right, with result left condition to right variable or expression value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.