Logical Operators: Or

The second logical operator is ||, meaning “or”. “If it's Saturday or Sunday, it's the weekend”:

const day = "Sunday";
if (day === "Saturday" || day === "Sunday") {
    console.log("It's the weekend");
}

This prints:

It's the weekend

A condition joined with || is true if at least one of its parts is true. It's false only if all the parts are false:

  • true || true is true
  • true || false is true
  • false || true is true
  • false || false is false

A typical mistake is to shorten the condition the way we speak: day === "Saturday" || "Sunday". JavaScript takes the right part on its own: it's just the text "Sunday", not a comparison. Text that isn't empty counts as true, so the whole condition is always true, even on Monday. Each part needs its own comparison: day === "Saturday" || day === "Sunday".

You can use && and || in one condition. Just as multiplication goes before addition, && goes before ||. Use parentheses to group what belongs together, as in math:

const day = "Saturday";
const temperature = 15;
if ((day === "Saturday" || day === "Sunday") && temperature > 20) {
    console.log("Let's go on a trip");
} else {
    console.log("Let's stay at home");
}

This prints:

Let's stay at home

The part in parentheses is evaluated first: it's Saturday, so it's true. But temperature > 20 is false, and true && false is false. Without the parentheses, JavaScript would first join day === "Sunday" && temperature > 20, and the condition would be true on every Saturday, whatever the weather.

Instructions

A movie theater gives a discount to students and to people aged 65 or more. Write an if statement that prints Discount if isStudent is true or age is at least 65. Use ||.

New rule: discounts only on Wednesdays. Add && day === "Wednesday" to the end of the condition, put parentheses around the || part, and add an else branch that prints Full price. Today is Monday, so the program prints Full price.

Start programming for free

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

Or sign up with:

8/11