DevPath · Learn to code ESPTEN

Conditionals

if, else if and else

Your program starts deciding

Until now your code was obedient: it ran line by line, top to bottom, no questions asked. Conditionals give it something new: the power to choose. "If this happens, do that; otherwise, do something else." It is the first step toward a program that feels a little bit smart, because it reacts differently depending on the data it receives.

The if structure

const age = 20;

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

What goes between parentheses is a condition: a yes-or-no question that evaluates to true or false. If the answer is true, the block between braces { } runs. If it is false, JavaScript skips it and walks right past.

Adding an else

The else is the "and if not...". It runs when the condition is not met, so you cover both possible paths:

const age = 15;

if (age >= 18) {
  console.log("You may come in");
} else {
  console.log("Access denied");
}

Several alternatives: else if

Life is rarely black or white. When there are more than two paths, you chain else if. JavaScript checks the conditions top to bottom and, the moment it finds a true one, it runs only that one and forgets the rest:

const grade = 7;

if (grade >= 9) {
  console.log("Outstanding");
} else if (grade >= 7) {
  console.log("Very good");
} else if (grade >= 5) {
  console.log("Pass");
} else {
  console.log("Fail");
}
// Prints "Very good"

⚠️ CLASSIC TRAP: the order of the conditions. Since JavaScript keeps the first one that is true, if you put grade >= 5 at the very top, a 10 would land in "Pass" and never reach "Outstanding"! A 10 is also greater than 5, of course. Golden rule: always put the most demanding conditions first and work your way down.

Examples

Do you let them into the concert?

const age = 16;
if (age >= 18) {
  console.log("Of legal age");
} else {
  console.log("Underage");
}

Message based on the exam grade

const grade = 8;
if (grade >= 9) {
  console.log("Outstanding");
} else if (grade >= 5) {
  console.log("Pass");
} else {
  console.log("Fail");
}
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Truthy/falsy and the ternary operator →