Use either “&&” or “||” i.e. logical AND or logical OR operator to connect two or multiple conditions inside a if statement in JavaScript. Multiple expression in if conditions is used to narrow down result.
AND: &&
// If x is 3 and y is 5 if(x == 3 && y == 5){ ... }
OR: ||
// If x is 3 or y is 5 if(x == 3 || y == 5){ ... }
JavaScript if multiple conditions
Simple example code to find the number which is divisible by both 5 and 7 ,using logical AND, which returns true only if both the conditions are true.
<!DOCTYPE html>
<html>
<body>
<script>
var x = 70;
if(x%5 == 0 && x% 7== 0){
console.log(" X divided by both 5 and 7");
}
</script>
</body>
</html
Output:
If you need to find out, is the number divisible by either 5 or 7? You need to use logical OR,
<script>
var x = 70;
if(x%5==0 || x%7 ==0){
console.log(" X divided by 5 OR 7");
}
</script>
Truth table for AND operator:
A | B | A && B |
---|---|---|
True | True | True |
True | False | False |
False | True | False |
False | False | False |
Example: The same example can be done with or operator.
var arr = [5,25,70,62,20,89];
arr.forEach(num => {
if (num == 20 && num%2 == 0){
console.log(num);
}
})
Using AND and OR Operators in Combination Inside the if Statement in JavaScript
var arr = [5,25,70,62,20,89];
arr.forEach(num => {
if ( (num != 20 && num%2 == 0) || (num > 50) && (num < 100)){
console.log(num);
}
})
Output:
70
62
89
Do comment if you have any doubts or suggestions on this JS if code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version