Combining Conditions with And, Or and Not
The logical operators && (and), || (or) and ! (not) join small true-or-false checks into one condition, so a single if can follow a real rule with several parts.
Apprentice · JavaScript · Updated
After this lesson you can
- Combine conditions with the and, or and not operators
- Group conditions with parentheses so a rule means what you intend
Key takeaways
&&is read "and": it'strueonly when the conditions on both sides aretrue.||is read "or": it'struewhen at least one side istrue.!is read "not": it flipstruetofalseand back.- JavaScript works out
&&before||, so put parentheses around an "or" that belongs together. - Each side of
&&and||needs a whole comparison:day === "Saturday" || "Sunday"is true on every day of the week.
Real rules seldom have only one part. Free shipping for members on orders over $35. The pool is open on Saturdays or Sundays. Show the Log in button when the visitor is not logged in. A store's checkout, a game's rules and a form's checks are full of rules like these. In JavaScript you join the parts with three small operators: and, or and not. Together they're called the logical operators.
Hilltop Bikes has a few rules with more than one part, and this lesson writes each of them.
And: both must be true
To rent a bike on your own at Hilltop Bikes, you must be 16 or older and have signed the safety waiver. One without the other isn't enough.
In JavaScript, "and" is written &&, two ampersands, and read "and". It's true only when the conditions on both sides are true:
const age = 17;
const signedWaiver = false;
if (age >= 16 && signedWaiver) {
console.log("You're all set. Enjoy the ride!");
} else {
console.log("Not yet: please sign the waiver at the counter.");
}
Not yet: please sign the waiver at the counter.
age >= 16 is true, but signedWaiver is false, so the whole condition is false. Change signedWaiver to true, and the rider is all set.
Or: at least one is true
Weekend prices apply on a Saturday or a Sunday. Either one is enough.
"Or" is written ||, two vertical bars, and read "or". On most keyboards the bar is above Enter, on the backslash key: hold Shift and press it. || is true when at least one side is true:
const day = "Sunday";
let hourlyRate = 12;
if (day === "Saturday" || day === "Sunday") {
hourlyRate = 15;
}
console.log(`On ${day}, a bike is ${hourlyRate} an hour.`);
On Sunday, a bike is $15 an hour.
With day set to "Tuesday", both sides are false, so the rate stays $12.
Not: flip it
Every rental gets the same question at the counter: Did you bring a helmet? If the answer is not yes, the shop offers one for $4.
"Not" is written !, an exclamation mark, read "not". It goes in front of a condition and flips it: !true is false, and !false is true.
const hasHelmet = false;
if (!hasHelmet) {
console.log("Add a helmet for $4?");
}
Add a helmet for $4?
Read if (!hasHelmet) aloud as "if not has helmet": it runs when hasHelmet is false. It's the same ! that starts !==, read "not strictly equal".
Here's the whole set in one table:
| Operator | Read | It's true when |
|---|---|---|
&& |
and | both sides are true |
\|\| |
or | at least one side is true |
! |
not | the condition after it is false |
Try it. In a file named rules.js, set const age = 15; and const withAdult = true;. Write an if that prints OK to ride when the rider is 16 or older or riding with an adult. Run it with node rules.js, then try an age of 15 with withAdult set to false.
Grouping with parentheses
Hilltop Bikes gives members a free helmet on weekends. That's two parts joined by "and": the rider is a member, and it's the weekend. And "the weekend" is itself two parts joined by "or". Put the "or" in parentheses, so it's worked out first, as one condition:
const isMember = true;
const day = "Saturday";
if (isMember && (day === "Saturday" || day === "Sunday")) {
console.log("Free helmet for members this weekend!");
} else {
console.log("Helmets are $4.");
}
Free helmet for members this weekend!
Why the parentheses? JavaScript works out && before ||, the same way it does * before +. Without them, the condition reads as "a member on a Saturday, or anyone at all on a Sunday", and every Sunday rider would get a free helmet, member or not. When a condition mixes && and ||, add the parentheses even where you think they're not needed: the next person to read it won't have to work out the order.
A mistake JavaScript won't catch
It's tempting to write "Saturday or Sunday" the way you'd say it:
const day = "Tuesday";
if (day === "Saturday" || "Sunday") {
console.log("Weekend prices: $15 an hour.");
} else {
console.log("Weekday prices: $12 an hour.");
}
Weekend prices: $15 an hour.
On a Tuesday, it charges weekend prices. The left side, day === "Saturday", is false. The right side is "Sunday" on its own: not a question at all, only some text. When JavaScript needs a true or false and gets something else, it decides for itself, and any text that isn't empty counts as true. A value that counts as true like that is called truthy. So the condition is true every day of the week.
JavaScript doesn't show an error: the program runs and quietly gives the wrong answer. The fix is a whole comparison on each side, day === "Saturday" || day === "Sunday".
Check yourself
2 questions to try on the lesson page.
So what
&&, || and ! let one if follow a real rule with several parts, and parentheses make sure JavaScript reads the rule the way you mean it.