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?
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.
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.
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 ."
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.
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)
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With