Control Flow

if, switch, loops

Control Flow in JavaScript

Control flow statements determine which code blocks execute and in what order. They're essential for creating dynamic, responsive applications.

If Statements

Execute code based on conditions:

const age = 18;

if (age >= 18) {
  console.log("You can vote");
}

// If-else
if (age >= 21) {
  console.log("You can drink alcohol");
} else {
  console.log("You're too young");
}

// If-else if-else
const score = 85;

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

Switch Statements

Better than multiple if-else when checking a single value:

const day = "Monday";

switch (day) {
  case "Monday":
    console.log("Start of the work week");
    break;
  case "Friday":
    console.log("Last day of work!");
    break;
  case "Saturday":
  case "Sunday":
    console.log("Weekend!");
    break;
  default:
    console.log("Regular weekday");
}

// Without break, execution "falls through"
const fruit = "apple";
switch (fruit) {
  case "apple":
  case "pear":
    console.log("This is a pome fruit");
    break;  // Important!
  case "banana":
    console.log("This is a berry");
    break;
}

For Loops

Repeat code a specific number of times:

// Classic for loop
for (let i = 0; i < 5; i++) {
  console.log(i);  // 0, 1, 2, 3, 4
}

// Loop through array
const fruits = ["apple", "banana", "orange"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

// For...of loop (modern, cleaner)
for (const fruit of fruits) {
  console.log(fruit);
}

// For...in loop (for object keys)
const person = { name: "Alice", age: 30 };
for (const key in person) {
  console.log(`${key}: ${person[key]}`);
}

While Loops

Repeat while a condition is true:

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

// Do-while (executes at least once)
let num = 0;
do {
  console.log(num);
  num++;
} while (num < 5);

Break and Continue

Control loop execution:

// Break: exit the loop entirely
for (let i = 0; i < 10; i++) {
  if (i === 5) break;
  console.log(i);  // 0, 1, 2, 3, 4
}

// Continue: skip to next iteration
for (let i = 0; i < 5; i++) {
  if (i === 2) continue;
  console.log(i);  // 0, 1, 3, 4 (skips 2)
}

⚠️ Common Pitfalls

  • • Forgetting break in switch statements causes fall-through
  • • Infinite loops: always ensure the condition eventually becomes false
  • • Off-by-one errors: i < array.length not i <= array.length

✓ Best Practices

  • • Use for...of for arrays (more readable than classic for loops)
  • • Use array methods like .forEach(), .map(), .filter() when appropriate
  • • Use switch when checking a single variable against multiple values
  • • Always include a default case in switch statements