I'm trying to check whether the variable y is less than x and greater than z, but this boolean expression is returning false for some reason. Does JavaScript allow boolean expressions to be written concisely like this? If so, what is the correct syntax?
x = 2;
y = 3;
z = 4;
if(x > y > z){
alert("x > y > z"); //Nothing happens!
}
Comparison operators — operators that compare values and return true or false . The operators include: > , < , >= , <= , === , and !== . Logical operators — operators that combine multiple boolean expressions or values and provide a single boolean output.
Logical Operators They evaluate expressions down to Boolean values, returning either True or False . These operators are and , or , and not and are defined in the table below. Logical operators are typically used to evaluate whether two or more expressions are true or not true.
JavaScript provides three different value-comparison operations: === — strict equality (triple equals) == — loose equality (double equals) Object.is()
Change your test to
if (x > y && y > z){
When you write (x > y > z)
, this is equivalent to ((x>y)>z)
, so you're comparing a boolean (x>y)
to z
. In this test, true
is converted to 1
, which isn't greater than 2
.
You want
if(x > y && y > z){
alert("x > y > z"); //Nothing happens!
}
Javascript will try to parse your original statement from left to right and you'll end up comparing z to a boolean value which will then be parsed to a number (0 or 1).
So your original statement is equivalent to
if( (x > y && 1 > z) || (x <= y && 0 > z))
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