Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 603
punkrockbuddyholly Avatar asked Nov 03 '10 16:11

punkrockbuddyholly


People also ask

What is the return value for true?

Note that these exceptions are not part of the C language itself, but rather with commonly-used C functions. Show activity on this post. In an if statement, or any case where a boolean value (True or false) is being tested, in C, at least, 0 represents false, and any nonzero integer represents true.

What does return true mean?

To check if a function returns true , call the function and check if its return value is equal to true , e.g. if (func() === true) . If the function's return value is equal to true the condition will be satisfied and the if block will run.

Why does true == true return false?

Because they don't represent equally convertible types/values. The conversion used by == is much more complex than a simple toBoolean conversion used by if ('true') . So given this code true == 'true' , it finds this: "If Type(x) is Boolean , return the result of the comparison ToNumber(x) == y ."

Is return true the same as return 0?

return 0 in the main function means that the program executed successfully. return 1 in the main function means that the program does not execute successfully and there is some error. return 0 means that the user-defined function is returning false. return 1 means that the user-defined function is returning true.


1 Answers

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).

like image 128
Alan Geleynse Avatar answered Oct 08 '22 14:10

Alan Geleynse