← Back to Tutorials Chapter 2

Control Flow

Control flow determines the order in which your code executes. JavaScript provides conditionals, loops, and iteration tools to control program execution.

Conditional Statements

if / else if / else

let score = 85;

if (score >= 90) {
  console.log("Grade: A");
} else if (score >= 75) {
  console.log("Grade: B");
} else if (score >= 60) {
  console.log("Grade: C");
} else {
  console.log("Grade: F");
}

Switch Statement

Use switch when comparing a single value against many possible cases:

let day = 3;
let dayName;

switch (day) {
  case 1:
    dayName = "Monday";
    break;
  case 2:
    dayName = "Tuesday";
    break;
  case 3:
    dayName = "Wednesday";
    break;
  case 4:
    dayName = "Thursday";
    break;
  case 5:
    dayName = "Friday";
    break;
  default:
    dayName = "Weekend";
}

console.log(dayName); // "Wednesday"
Remember: Always include break in each case unless you intentionally want fall-through. The default clause runs when no case matches.

Ternary Operator

A shorthand for simple if/else conditions:

let age = 20;
let status = age >= 18 ? "Adult" : "Minor";
console.log(status); // "Adult"

Loops

for Loop

for (let i = 0; i < 5; i++) {
  console.log("Iteration:", i);
}
// Prints 0, 1, 2, 3, 4

while Loop

let count = 0;
while (count < 5) {
  console.log(count);
  count++;
}

do-while Loop

Executes the body at least once, then checks the condition:

let x = 0;
do {
  console.log(x);
  x++;
} while (x < 3);

Iteration Methods

for...of

Iterates over iterable values (arrays, strings, etc.):

let colors = ["red", "green", "blue"];
for (let color of colors) {
  console.log(color);
}

for...in

Iterates over enumerable property keys of an object:

let person = { name: "Alice", age: 30 };
for (let key in person) {
  console.log(key + ":", person[key]);
}

Jump Statements

break exits a loop entirely. continue skips the current iteration and moves to the next one.

for (let i = 0; i < 10; i++) {
  if (i === 3) continue; // Skip 3
  if (i === 7) break;    // Stop at 7
  console.log(i);
}
// Prints: 0, 1, 2, 4, 5, 6
Control flow diagram showing conditional paths
Best Practice: Use for...of for arrays and for...in for objects. Avoid for...in on arrays since it iterates over keys (indices as strings) and may include inherited properties.
Exercise: Write a loop that prints all even numbers from 1 to 20. Then convert the same logic into a while loop. Finally, create a switch statement that maps a numeric month (1—12) to its name and logs it.