Sometimes one question isn't enough. You need to combine several. To ride a rollercoaster, you need to be tall enough and have a ticket. To get a discount, you need to be a student or a senior citizen.
JavaScript has three logical operators for combining booleans:
| Operator | Name | Meaning |
|---|---|---|
&& | AND | true only if both sides are true |
|| | OR | true if at least one side is true |
! | NOT | flips true to false and false to true |
(The || symbol is two "pipe" characters. On most keyboards, the pipe | is on the same key as the backslash \, above Enter. You'll need Shift to type it.)
AND: &&
Both conditions have to be true:
const height = 140;
const hasTicket = true;
const canRide = height >= 120 && hasTicket;
console.log(canRide);
It prints
true
| A | B | A && B |
|---|---|---|
| true | true | true |
| true | false | false |
| false | true | false |
| false | false | false |
OR: ||
At least one condition has to be true:
const isStudent = false;
const isSenior = true;
const getsDiscount = isStudent || isSenior;
console.log(getsDiscount);
It prints
true
| A | B | A || B |
|---|---|---|
| true | true | true |
| true | false | true |
| false | true | true |
| false | false | false |
NOT: !
! flips a boolean to its opposite. It's like the word "not" in English:
const isRaining = false;
console.log(!isRaining);
console.log(!true);
console.log(!!true);
It prints
true false true
!isRaining reads as "not raining," which is true here because it isn't raining. And !!true flips twice, back to true again. (Like saying "I'm not not hungry.")
Combining them
You can combine these operators to ask more complicated questions. Use parentheses to keep things clear:
const age = 25;
const hasLicense = true;
const isDrunk = false;
const canDrive = age >= 18 && hasLicense && !isDrunk;
console.log(canDrive);
const isWeekend = true;
const isHoliday = false;
const isSunny = true;
const goToBeach = (isWeekend || isHoliday) && isSunny;
console.log(goToBeach);
It prints
true true
Read the second one out loud: "If it's the weekend or a holiday, and it's sunny, go to the beach." Code that reads like a sentence is good code.
JavaScript is lazy (in a good way). With &&, if the left side is false, the whole thing must be false, so JavaScript doesn't even bother looking at the right side. With ||, if the left side is true, the answer must be true, so it skips the right side. This is called short-circuit evaluation. It sounds like a minor detail, but it enables some very handy tricks that we'll explore in Grade 13.