Choosing with if / else

Running code only when a condition is true

10 min read · runnable Javascript

Programs become powerful when they can make decisions. The if statement runs a block of code only if a condition is true.

let age = 20;

if (age >= 18) {
  console.log("You are an adult.");
}

Reading that: if age is greater than or equal to 18, then print the message. If the condition is false, the code inside the curly braces { } is skipped.

Adding an else

Use else to provide a backup plan for when the condition is false:

let age = 12;

if (age >= 18) {
  console.log("You are an adult.");
} else {
  console.log("You are a minor.");
}

More than two paths: else if

For several options, chain conditions with else if:

let score = 75;

if (score >= 90) {
  console.log("Grade A");
} else if (score >= 70) {
  console.log("Grade B");
} else {
  console.log("Keep practising!");
}

JavaScript checks each condition from top to bottom and runs the first one that is true, then skips the rest.

Tip: The condition inside the round brackets must produce a boolean (true or false). Those comparison operators you learned earlier are exactly what go here.

Try it yourself

Change the value of score and run the code to see different branches run.

Try it yourself
Output
Press “Run code” to see the result.

Quick check

Q1 When does the code inside an if block run?

Q2 In an if / else if / else chain, how many blocks run?

Want to save your progress? It's free.

Create a free account