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

Logical Operators: And

Sometimes one condition isn't enough. “If it's Friday and it's warmer than 20 °C, I'll go out” is made of two conditions joined by the word “and”. In JavaScript, “and” is written &&:

const day = "Friday";
const temperature = 25;
if (day === "Friday" && temperature > 20) {
    console.log("I'm going out");
}

This prints:

I'm going out

&& is a logical operator: it joins two conditions into one. The joined condition is true only if both parts are true. If even one of them is false, the whole condition is false:

  • true && true is true
  • true && false is false
  • false && true is false
  • false && false is false

You can join more conditions in a row: a && b && c is true only if all three are true.

Each part must be a complete comparison. “Age from 13 to 19” is age >= 13 && age <= 19. If you write age >= 13 && <= 19, the program ends with SyntaxError: Unexpected token '<='. And 13 <= age <= 19, as in math, runs without an error but gives wrong results (it's true even for an age of 25), because JavaScript compares only two values at a time.

Instructions

  1. 1

    Write an if statement that prints Welcome only if username is "admin" and at the same time password is "kitten42". Join the two comparisons with &&.

  2. 2

    Add an else branch that prints Wrong username or password. Then try a wrong password: change password to "kitten". One false part is enough to make the whole condition false, so the program prints Wrong username or password.

Back

8/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.