Making Decisions with if

Grade 4, page 1 of 11. A two-minute read.

Every day, you make hundreds of tiny decisions without even thinking about them.

If it's raining, take an umbrella. If you're hungry, eat something. If the phone battery is low, plug it in. If someone says "the last slice of pizza is for whoever wants it," move fast.

Programs need to make decisions too. If the password is correct, log the user in. If the player's health reaches zero, show "Game Over." If the cart is empty, disable the checkout button.

A decision: one question, two possible paths

In JavaScript, decisions are made with the if statement:

JavaScript
const isRaining = true;

if (isRaining) {
  console.log("Take an umbrella! ☂️");
}

console.log("Have a nice day!");

It prints

Take an umbrella! ☂️
Have a nice day!

Here's how it works:

  1. The keyword if starts the decision.
  2. Inside the parentheses ( ) goes the condition: a question that's either true or false.
  3. Inside the curly braces { } goes the code to run only if the condition is true. This is called the block.

If the condition is false, JavaScript skips the entire block and carries on with whatever comes after it:

JavaScript
const isRaining = false;

if (isRaining) {
  console.log("Take an umbrella! ☂️");
}

console.log("Have a nice day!");

It prints

Have a nice day!

The umbrella message was skipped completely. But "Have a nice day!" is outside the if block, so it always runs.

Using comparisons as conditions

Most of the time, the condition will be a comparison from Grade 3:

JavaScript
const temperature = 34;

if (temperature > 30) {
  console.log("It's hot! Drink some water. 🥤");
}

const score = 100;

if (score === 100) {
  console.log("PERFECT SCORE! 🏆");
}

It prints

It's hot! Drink some water. 🥤
PERFECT SCORE! 🏆
TipIndent your blocks

Notice how the code inside the curly braces is pushed in by two spaces? That's called indentation. JavaScript doesn't need it, but humans do. It makes it instantly obvious which code belongs inside the if. VS Code will usually indent for you automatically. You can also tidy up a whole file with Format Document (right-click in the editor to find it).

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