Information about cookies on this page

Our website uses cookies to ensure the functionality of the website, to collect and analyze information about the performance and usage of the website. Privacy Policy

  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in
  
  • Courses
    • Discord
    • Twitter
    • Linkedin
    • Facebook
    • Instagram
  • Pricing
  • English
  • Čeština
  • Deutsch
  • Русский
Sign inStart free
  • Courses
  • Pricing

Community

Sign in

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 needed

isRaining 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. 1

    Write an if statement that prints I will go outside if the internet doesn't work. Use !.

  2. 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 an else branch that prints I will read a book.

Back

11/13

  1. 1. The if Statement
  2. 2. The else Branch
  3. 3. Comparison Operators
  4. 4. Assign or Compare?
  5. 5. Quiz: Assign or Compare?
  6. 6. Boolean Values
  7. 7. More Options: else if
  8. 8. Logical Operators: And
  9. 9. Logical Operators: Or
  10. 10. Quiz: Logical Operators
  11. 11. Negation
  12. 12. Nested Conditions
  13. 13. Summary
Next

Try it yourself

Do this exercise right here in your browser. No account needed.