The FundamentalsSunday, January 25, 2026

Control Flow

If statements, loops, and logic.

Advertisement

Support JS Mastery Path by checking out our sponsors.

Without control flow, code reads from top to bottom like a book. Control flow allows your code to make decisions, skip sections, or repeat tasks. It creates intelligence.

The Fork in the Road

Imagine driving a car. You reach an intersection:
IF the light is green, drive.
ELSE IF the light is yellow, slow down.
ELSE (the light must be red), stop.

You only execute one of these actions. You don't drive AND stop at the same time.

If / Else Logic

The code inside the { } blocks only runs if the condition in the ( ) is true.

const batteryLevel = 15;

if (batteryLevel > 20) {
  console.log("Battery is fine.");
} else if (batteryLevel > 5) {
  // This runs because 15 is NOT > 20, but IS > 5
  console.log("Low battery! Please charge.");
} else {
  console.log("Phone is shutting down...");
}

Loops (Repetition)

Programmers hate doing the same thing twice. If you need to send an email to 100 users, you don't write the email code 100 times. You write it once and put it in a loop.

The "For" Loop

Use this when you know exactly how many times to loop.

for (start; stop condition; step)
  • Start: Create a counter (let i = 0).
  • Stop: Keep going as long as this is true (i < 5).
  • Step: What to do after each round (i++ means add 1).
for (let i = 0; i < 5; i++) {
  console.log("Iteration number: " + i);
}
console.log("Loop finished!");

The "While" Loop

Use this when you don't know how many times to loop, but you know the condition to stop (e.g., "Keep driving until the tank is empty").

let fuel = 30;

while (fuel > 0) {
  console.log("Vroom! Fuel left: " + fuel);
  fuel = fuel - 10; // Burn fuel
}

console.log("Car stopped.");

Danger: Infinite Loops

If you forget to change the variable (like `fuel`), the condition `fuel > 0` will ALWAYS be true. The loop will run forever and crash your browser.

Advertisement

Support JS Mastery Path by checking out our sponsors.