Logical Operators AND and OR
The logical operators combine several conditions into one, which makes a compound condition for an if statement:
| Operator | Name | The result is truthy when |
|---|---|---|
a && b |
AND | both a and b are truthy |
a || b |
OR | at least one of a and b is truthy |
!a |
NOT | a is falsy |
Combining conditions
Section titled “Combining conditions”const basket = ['bread', 'butter', 'jam'];const has = (item) => basket.includes(item);
if (has('bread') && has('butter')) { console.log('Ready for toast.');}
if (has('milk') || has('juice')) { console.log('Something to drink.');} else { console.log('Nothing to drink.');}
if (!has('tea')) { console.log('Add tea to the list.');}This prints:
Ready for toast.Nothing to drink.Add tea to the list.basket.includes(item) returns true when the array contains the item, so has gives a boolean that the operators can combine. Any number of conditions can be chained, as in has('milk') || has('juice') || has('water').
Which operator goes first
Section titled “Which operator goes first”&& binds more tightly than ||, in the same way that multiplication binds more tightly than addition. So a || b && c means a || (b && c), which is not always what was meant:
const isMember = true;const total = 30;const hasVoucher = false;
console.log(isMember || total > 50 && hasVoucher);console.log((isMember || total > 50) && hasVoucher);This prints:
truefalseThe first line reads as “a member, or a large order with a voucher”. The second reads as “a member or a large order, and in either case a voucher”. Where a condition mixes && and ||, add brackets so the grouping is visible, even where the default happens to be right.
Checking a range
Section titled “Checking a range”A value between two limits needs two comparisons joined with &&. The form used in mathematics does not work:
const age = 34;
console.log(age >= 18 && age <= 65);console.log(18 <= age <= 65);console.log(18 <= 99 <= 65);This prints:
truetruetrue18 <= 99 <= 65 is worked out from left to right: 18 <= 99 gives true, and true <= 65 converts true to 1, which gives true again. The chained form gives true for every age, because the first comparison leaves either 1 or 0, and both are at most 65, so only the first line is a real range check.
What the operators return
Section titled “What the operators return”&& and || do not always return true or false. They return one of their two operands, which only looks like a boolean when the operands are booleans. Inside an if the difference does not matter, but it is useful elsewhere, as Conditional Operand Selectors shows. They also stop as soon as the answer is known, which Logical Short Circuiting covers.
Steve Griffith covers this topic in his video Logical Operators AND and OR with Compound if statements.