An AND condition requires all of its conditions to return true
in order to resolve to true
itself.
Conversely, an OR condition looks for any of its conditions to return true
.
We use two pipe characters (||
) to create an OR condition. An OR condition resolves to true
if either side returns true
:
if (1 + 1 === 3 || 10 > 9) {
console.log("one of them returned true!");
}
OR in Functions
Here's an example of an OR condition inside a function. Try calling the function with different arguments:
function checkIfAdmin(username) {
if (username === "BillGates" || username === "PaulAllen") {
return true;
}
else {
return false;
}
}
checkIfAdmin("ElonMusk");
Chaining OR Conditions
We can chain as many conditions as we want into a single statement:
if (1 * 1 > 10 || 2 * 2 > 10 || 3 * 3 > 10 || 4 * 4 > 10) {
"squaring a number less than 5 gives a value greater than 10";
}
It is best to keep statements simple and readable. Don't try to create the longest conditional statement you can. It is better to break them up into separate if
statements so it's easy to read through the code and follow the logic.
OR Conditions are Lazy
An OR condition actually runs from left to right. As soon as it reaches a condition that returns true
, it will stop executing and return true
itself. Any conditions after that won't execute because they are redundant.
Mixing AND with OR
You may want to create a condition that includes both AND and OR operators. In that case, any AND operators will run first, just like multiplication always happens before addition.
However, it is best to use parentheses to clearly group the conditions that you want to run first. It can be confusing to look at a mix of AND and OR conditions that are not grouped by parentheses.