Logical Operators
Sometimes we need to combine multiple conditions. For example, if it's Saturday or Sunday, it's the weekend. By using the word or, we combine two conditions. In code, we write this as: ||
. Here's how we would implement this example in code:
let day = "Saturday";
if (day === "Saturday" || day === "Sunday") {
console.log("It's the weekend");
}
// Prints: It's the weekend
Besides or ||
, we have another logical operator that combines multiple conditions: and &&
. For example, if it's Friday and the temperature is above 20°C, I will go outside:
let day = "Friday";
let temperature = 25;
if (day === "Friday" && temperature > 20) {
console.log("I'm going outside");
}
// Prints: I'm going outside
We can combine these operators as many times as we need and use parentheses to determine precedence. For example:
let day = "Friday";
let temperature = 25;
if ((day === "Friday" || day === "Saturday" || day === "Sunday") && temperature > 20) {
console.log("I'm going outside");
}
// Prints: I'm going outside
Instructions
Use an if
statement to print Welcome
if the username is admin
and &&
the password is 123456
.
Start programming for free
6/9