Why does 3>2>1
return false
while 1 < 2 < 3
returns true
?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
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 ."
It simply stops the execution of the function(). That means, it will end the whole execution of process.
Using return causes your code to short-circuit and stop executing immediately. The first return statement immediately stops execution of our function and causes our function to return true . The code on line three: return false; is never executed.
Hence, the return statement is passing the value x*x back to the call of square . If you want to view the value in ans, you would write: console. log(ans); or to simplify the problem as a whole you could write: console. log(square(5)); and my guess is you have this last line in your code which is why you are confused.
Since 1 < 2
evaluates to true
and 3 > 2
evaluates to true
, you're basically doing :
console.log(true < 3);
console.log(true > 1);
And true
is converted to 1
, hence the results.
Because it interprets left to right and because it tries to cast to same type.
1 < 2 < 3
becomes true < 3
, which because we are comparing numbers is cast to 1 < 3
which is truth.
3 > 2 > 1
becomes true > 1
, which because we are comparing numbers is cast to 1 > 1
which is false.
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