To check multiple conditions in an if statement, combine them using logical operators like "and" (&&), "or" (||), or "not" (!). These operators determine whether all, any, or none of the conditions must be true for the code block to execute.
Logical operators evaluate expressions as either true or false. For example:
if (x > 0 && y < 10) {
// Code executes only if both conditions are true
}
Here, the && operator ensures both conditions must be true. The || operator would require only one condition to be true, while ! negates a condition.
There are three primary ways to structure multiple conditions:
For example, checking if a value is between 1 and 10 requires both an AND and an OR:
if (value >= 1 && value <= 10) {
// Value is between 1 and 10
}
Developers use multiple conditions to create precise logic flows. For instance, validating user input often requires checking multiple criteria. A login system might verify both username and password:
if (username === "admin" && password === "secret") {
// Grant access
}
Without multiple conditions, developers would need nested if statements, making code harder to read and maintain.
Many beginners confuse the order of evaluation. Logical operators follow precedence rules: NOT first, then AND, then OR. Parentheses override these rules. For example:
if (x > 5 || y < 3 && z === 10) {
// This evaluates as (x > 5) OR (y < 3 AND z === 10)
}
To force a different evaluation order, use parentheses:
if ((x > 5 || y < 3) && z === 10) {
// Now (x > 5 OR y < 3) must be true AND z must equal 10
}
Let's build a function that checks if a string is either empty or contains only whitespace:
function isEmptyOrWhitespace(str) {
const condition1 = str.length === 0;
const condition2 = str.trim().length === 0;
if (condition1 || condition2) {
return true;
} else {
return false;
}
}
console.log(isEmptyOrWhitespace("")); // true
console.log(isEmptyOrWhitespace(" ")); // true
console.log(isEmptyOrWhitespace("hello")); // false
This example uses the OR operator to check two distinct conditions. The function returns true if either condition is met.
When writing multiple conditions, always test edge cases to ensure your logic behaves as expected. For more on logical conditions, see this guide.