Friday 22 November 2019

javascript - 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?


Answer



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


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...