← JS Mastery | Module 2: Control Flow Break, Continue & Nested Loops
Module 2

Break, Continue & Nested Loops

ā± 14 min read ā— Beginner šŸ†“ Free

Break — Exiting a Loop Early

// break exits the loop immediately
const numbers = [1, 3, 7, 2, 9, 4, 6];

// Find first even number
let firstEven;
for (const num of numbers) {
  if (num % 2 === 0) {
    firstEven = num;
    break;  // stop searching once found
  }
}
console.log(firstEven); // 2

// Without break: find in array using find() — cleaner:
const firstEven2 = numbers.find(n => n % 2 === 0);

// break in while loops
let attempts = 0;
while (true) {  // infinite loop
  attempts++;
  if (attempts >= 5) break;  // manual termination
}

// break in switch (as seen earlier):
switch (value) {
  case "a":
    doA();
    break;  // without this, falls through to next case!
  case "b":
    doB();
    break;
}

Continue — Skip to Next Iteration

// continue skips the rest of current iteration, moves to next
for (let i = 0; i < 10; i++) {
  if (i % 2 === 0) continue;  // skip even numbers
  console.log(i);  // prints only: 1, 3, 5, 7, 9
}

// Process only valid items:
const data = [1, null, 3, undefined, 5, "", 7];
for (const item of data) {
  if (!item) continue;  // skip falsy values
  console.log(item * 2);  // 2, 6, 10, 14
}

// Often cleaner with filter:
data.filter(Boolean).forEach(item => console.log(item * 2));

Nested Loops & Labels

// Nested loops — matrix/grid operations
for (let row = 0; row < 3; row++) {
  for (let col = 0; col < 3; col++) {
    console.log(`[${row},${col}]`);
  }
}

// break in nested loops only breaks the inner loop:
outer: for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 3; j++) {
    if (i === 1 && j === 1) {
      break outer;  // breaks the OUTER loop
    }
    console.log(i, j);
  }
}

// Finding a pair in a 2D array:
const matrix = [[1,2,3],[4,5,6],[7,8,9]];
let target = 5, foundRow, foundCol;
search: for (let r = 0; r < matrix.length; r++) {
  for (let c = 0; c < matrix[r].length; c++) {
    if (matrix[r][c] === target) {
      foundRow = r; foundCol = c;
      break search;
    }
  }
}
console.log(`Found at [${foundRow},${foundCol}]`); // [1,1]

⚔ Key Takeaways

šŸŽÆ Practice Exercises

EXERCISE 1

Write a loop that prints numbers 1-100, but stops when it hits the first number divisible by both 7 AND 11. Use break.

EXERCISE 2

Create a 5x5 multiplication table using nested loops, storing the result as a 2D array, then display it neatly formatted.

← Ternary Operator