Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple comparison operators in a JavaScript boolean expression

Tags:

javascript

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!
}
like image 797
Anderson Green Avatar asked May 20 '13 18:05

Anderson Green


People also ask

What are the six Boolean comparison operators?

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.

What type of operators compare two Booleans?

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.

How many comparison operators are there in JavaScript?

JavaScript provides three different value-comparison operations: === — strict equality (triple equals) == — loose equality (double equals) Object.is()


2 Answers

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.

like image 112
Denys Séguret Avatar answered Sep 27 '22 19:09

Denys Séguret


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))
like image 36
Ben McCormick Avatar answered Sep 27 '22 21:09

Ben McCormick