JavaScript

This page explains how if, else if, and else choose which code block runs.

Goal: branch safely based on conditions and make the order of checks easy to understand.

if...else

An if statement runs its block when its condition is truthy. If the condition is false, an optional else block can run instead.

JavaScript

const age = 20;

if (age >= 18) {
  console.log("Adult");
} else {
  console.log("Under 18");
}

Several cases with else if

JavaScript

const score = 82;

if (score >= 90) {
  console.log("A");
} else if (score >= 70) {
  console.log("B");
} else {
  console.log("C");
}

JavaScript checks the conditions from top to bottom and runs the first matching block. Once a block runs, the remaining branches are skipped.

Build clear conditions

Comparison operators such as ===, >, and <= produce Booleans. Logical operators such as &&, ||, and ! combine conditions.

JavaScript

const age = 20;
const hasTicket = true;

if (age >= 18 && hasTicket) {
  console.log("May enter");
}

Practical tips

Related topics