Combining Conditions

Grade 4, page 5 of 11. A one-minute read.

Remember the logical operators from Grade 3? They're perfect inside if statements:

JavaScript
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. ⏰
Watch outThe classic OR bug

This might be the most common beginner bug in all of programming. Can you spot it?

JavaScriptHas a bug
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:

JavaScriptFixed
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).

Reading is step one

CurlyScript turns these notes into a game: short questions, an explanation after every answer, and a test at the end of each grade. Free, with nothing to sign up for.

Start learning