Negation
The third logical operator, !, is called negation. It turns a boolean into its opposite: !true is false and !false is true. Read it as “not”:
const isRaining = false;
if (!isRaining) {
console.log("No umbrella needed");
}This prints:
No umbrella neededisRaining is false, so !isRaining is true and the block runs. Read the condition as “if it is not raining”. You could also write isRaining === false; it means the same, but ! is shorter. You already know ! from !==, “not equal”.
Negation comes in handy when you combine conditions. “The shop is open and it isn't a holiday” is isOpen && !isHoliday.
To negate a comparison, put it in parentheses: !(age >= 18) means “age is not 18 or more”. Without them, the ! would apply only to age, and !age >= 18 would give wrong results. In this case, age < 18 is simpler anyway.
Instructions
- 1
Write an
ifstatement that printsI will go outsideif the internet doesn't work. Use!. - 2
Going outside is only fun when it isn't raining. Extend the condition with
&&so that it's true only if the internet doesn't work and it isn't raining (!isRaining). Then add anelsebranch that printsI will read a book.