Use And (&&) or OR (||) statement to get the if statement with multiple conditions in JavaScript. Just make sure you wrap your conditions in parentheses required to evaluate in the order that you want them evaluated.
Here is a couple of option depending on what you are up to gain:
&& - and // if conditions 1 and 2 are true do something If (cond1 && cond2) { Do something } || - or // if conditions 1 or 2 are true do something If (cond1 || cond2) { Do something } ! == - not // if conditions 1 is not equal to 2 do something If (cond1!== cond2) { Do something }
Multiple conditions are just a boolean expression:
if (condition1 && condition2 || condition3) { ... }
JavaScript if statement multiple conditions
A simple example code to check a given number is divisible by 5 and 7.
<!DOCTYPE html>
<html>
<body>
<script>
var x = 35;
if(x%5==0 && x%7==0){
console.log(x,"Divisible by 5 and 7")
}
</script>
</body>
</html>
Output:
OR
If you need to find out, is the number divisible by either 5 or 7? You need to use logical OR.
if(x%5==0 || x%7 ==0){
// code
}
Here’s a practical example:
let age = 25;
let isStudent = true;
if (age >= 18 && age <= 30 && isStudent) {
console.log("You qualify for a student discount.");
} else {
console.log("You do not qualify for a student discount.");
}
In this example, the code block will execute if the age
is between 18 and 30 (inclusive) and the isStudent
variable is true
. If any of these conditions is not met, the else
block will execute.
Do comment if you have any doubts or suggestions on this Js if statement topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version