Combining Conditions with &&, ||, and !
Introduction
Welcome back! We have compared values and seen that each comparison gives us a boolean answer: true or false. Real questions often depend on more than one fact, such as whether the shop is open and whether it has any stock.
In this lesson, we will combine boolean answers with &&, ||, and !. We will store the resulting conditions under meaningful names and report them with template literals. This is the last unit in this course, so we will finish with a small decision report that uses the ideas we have built so far.
Both Sides with &&
The operator && combines two conditions. Its result is true only when both sides are true. Suppose the shop can serve customers only if it has stock and is open:
The first condition has two true sides. In the second, stock is not zero, so one side is false even though the shop is open:
We can read the first condition as “stock is above zero and the shop is open.” In this lesson, we combine boolean conditions, so each side gives a true or false answer and the combined result is boolean too.
At Least One Side with ||
The operator || combines conditions when either one is enough. Its result is true when at least one side is true, and false only when both sides are false:
The stock is not greater than 100, and happy hour is false, so neither condition holds. The output is:
If we changed isHappyHour to true, the result would be true even though the stock condition remains false. For these examples, both sides are boolean conditions, and either one may make the combined condition true.
Flip an Answer with !
The operator ! flips a boolean: it turns true into false and false into true. We place it directly before the value or condition we want to flip:
The first two lines show a stored answer and its opposite. The final line flips the complete comparison in parentheses: stock is not above zero, so its opposite is true.
Parentheses make clear which comparison ! flips. This is useful whenever we need the opposite of a state or a complete yes-or-no question.
