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

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 &&.

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.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

8/13

Next