Remember the logical operators from Grade 3? They're perfect inside if statements:
const age = 16;
const hasPermission = true;
if (age >= 13 && age <= 19) {
console.log("You're a teenager!");
}
if (age >= 18 || hasPermission) {
console.log("You can go on the school trip.");
}
const isWeekend = false;
if (!isWeekend) {
console.log("It's a school day. ⏰");
}
It prints
You're a teenager! You can go on the school trip. It's a school day. ⏰
This might be the most common beginner bug in all of programming. Can you spot it?
const color = "green";
if (color === "red" || "blue") {
console.log("You picked red or blue!");
}
It prints
You picked red or blue!
But the color is green! What happened?
JavaScript doesn't read this the way we would in English. It reads it as: (color === "red") || ("blue"). The first part is false. But the second part is just the string "blue" on its own, which is truthy! So the whole condition is true.
The fix is to write out the full comparison on both sides:
const color = "green";
if (color === "red" || color === "blue") {
console.log("You picked red or blue!");
} else {
console.log("You picked something else.");
}
It prints
You picked something else.
The same goes for ranges. You can't write if (age > 12 && < 20). You have to write if (age > 12 && age < 20).