Why does (0 < 5 < 3) return true?

04/30/2020 15:00:01

I was playing around in jsfiddle.net and I'm curious as to why this returns true?

if(0 < 5 < 3) {
    alert("True");
}

So does this:

if(0 < 5 < 2) {
    alert("True");
}

But this doesn't:

if(0 < 5 < 1) {
    alert("True");
}

Is this quirk ever useful?

Verified Answer (440 Votes)

11/03/2010 21:34:58

Order of operations causes (0 < 5 < 3) to be interpreted in javascript as ((0 < 5) < 3) which produces (true < 3) and true is counted as 1, causing it to return true.

This is also why (0 < 5 < 1) returns false, (0 < 5) returns true, which is interpreted as 1, resulting in (1 < 1).

440

Answer #2 (63 Votes)

11/03/2010 21:34:48

My guess is because 0 < 5 is true, and true < 3 gets cast to 1 < 3 which is true.

63

Answer #3 (21 Votes)

11/03/2010 21:36:05

probably because true is assumed as 1 so

0 < 5 < 3  -->  true < 3 -->  1 < 3  --> true
21
3
Hack Hex uses Stack Exchance API by the Stack Exchange Inc. to scrape questions/answers under Creative Commons license.