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";
}
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
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
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)