Question

So I wondered to myself if there is a way to do a double greater than, like this:

if(x > y > z) { ... }

Then I saw this Expression for "more than x and less than y"?

But then I tried the following expression in the console and got a weird result:

(5 < 2 < 1) // returned true
(5 > 2 > 1) // returned false

How?

Update: I know that you can't do this "(x > y > z)", just wanted explanation on the weird result.

Was it helpful?

Solution

You need two separate conditions, such as 5<2 && 2<1 for this to do what you're after. Without two conditions, you are comparing the result of the first condition against the right side of the second condition.

Why?

For the unexplained behaviour, I believe that the explanation for why it's returning what it's returning is the way javascript handles booleans (among other things) when used in numerical operations, in other words, javascript will cast your booleans to 0 or 1, there are a lot of examples of this in a few questions here at so, for example this one, you could do +false and get a 0 for instance.

(5 < 2 < 1) is true because:

  • 5<2 is resolved first, returning false
  • false is cast to a number, returning 0
  • 0<1 will return true

(5 > 2 > 1) is false because:

  • 5>2 is resolved first, will return true
  • true is cast to a number, will return 1
  • 1>1 will return false

OTHER TIPS

No. You can't do this in JavaScript. Much as it would be useful, you're stuck with x > y && y > z.

That said, to explain your result:

5 < 2 gives false
false casts to 0
0 < 1 is true

And:

5 > 2 gives true
true casts to 1
1 > 1 is false

As far as a "way to do a double greater than", you could define a function:

function gt () {
    var prev = arguments[0];
    return !([].slice.call(arguments, 1).some(function (arg) {
        var ret = prev <= arg;
        prev = arg;
        return ret;
    }));
}

...then call like this:

if(gt(x, y, z)) { ... }

I would just try if((5>2) && (2>1)) { } not sure why the other one didnt work but thus implementation should be a proper substitute for code that could be written in the other way you have it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top