DEV Community

Randy Rivera
Randy Rivera

Posted on

Comparisons with the Logical and Operator

Comparisons with the Logical And Operator

Sometimes you will need to test more than one thing at a time. The logical and operator (&&) returns true if and only if the operands to the left and right of it are true.

The same effect could be achieved by nesting an if statement inside another if:

  • Example:
function test(num) {
 if (num >= 25) {
  if (num <= 55) {
    return "Yes";
  }
}
return "No";
}
Enter fullscreen mode Exit fullscreen mode

This will only return Yes if num is greater than or equal to 25 and less than or equal to 55. The same logic can be written as:

function test(num) {
 if (num >= 25 && num <= 55) {
  return "Yes"; 
}
return "No";
}

test(10); // will display No if console.log 
Enter fullscreen mode Exit fullscreen mode

Here we replaced the two if statements with one statement, using the && operator, which will return the string Yes if val is less than or equal to 50 and greater than or equal to 25. Otherwise, will return the string No.

Comparisons with the Logical Or Operator

The logical or operator (||) returns true if either of them is true. Otherwise, it returns false.

The logical or operator is composed of two pipe symbols: (||). This can be found between your Backspace and Enter keys.

  • Example:
function test(num) {
  // Only change code below this line
  if (num < 10 || num > 20) {
    return "Outside";
  }
  return "Inside";
}

test(15); // will display Inside
Enter fullscreen mode Exit fullscreen mode

Here we Combined the two if statements into one statement which returns the string Outside if val is not between 10 and 20, inclusive. Otherwise, return the string Inside.

Top comments (0)