Home Module 09 Loops

1. Introduction

Loops let you repeat a block of code multiple times without writing it out manually. Imagine rendering 100 product cards on a page, or checking every item in a shopping cart — without loops you would have to copy-paste the same code 100 times.

JavaScript has several loop types. This lesson covers the three you will use most:

  • for — when you know how many times to repeat
  • while — when you repeat until a condition becomes false
  • for...of — when you iterate over every item in an array or string

You will also learn break and continue — two keywords for controlling loop flow.

2. Theory

2.1 The for loop

The most common loop. It has three parts in the parentheses:

  1. Initialiser — runs once before the loop starts (let i = 0)
  2. Condition — checked before every iteration; loop stops when false (i < 5)
  3. Update — runs after every iteration (i++)
for (let i = 0; i < 5; i++) {
  console.log('Iteration:', i);
}
// → 0, 1, 2, 3, 4

// Count down
for (let i = 10; i >= 0; i--) {
  console.log(i);
}

// Count by 2
for (let i = 0; i <= 10; i += 2) {
  console.log(i); // 0, 2, 4, 6, 8, 10
}

Looping over an array with for

const fruits = ['apple', 'banana', 'cherry'];

for (let i = 0; i < fruits.length; i++) {
  console.log(i, fruits[i]);
}
// → 0 'apple'
// → 1 'banana'
// → 2 'cherry'

2.2 The while loop

Runs as long as a condition is true. Use when you do not know how many iterations are needed up front.

let count = 0;

while (count < 5) {
  console.log('count:', count);
  count++;
}
// → 0, 1, 2, 3, 4

// Real use: waiting for user input (conceptually)
let userInput = '';
while (userInput.trim() === '') {
  userInput = prompt('Please enter your name:') ?? '';
}
console.log('Hello,', userInput);
Warning: Always make sure the loop condition eventually becomes false, or you create an infinite loop that freezes the browser tab.

2.3 The do...while loop

Like while, but the body runs at least once even if the condition starts false:

let x = 10;

do {
  console.log('x is', x); // runs once even though 10 < 5 is false
  x++;
} while (x < 5);
// → 'x is 10' (runs once, then stops)

2.4 The for...of loop

The cleanest way to iterate over every item in an array (or any iterable — strings, Sets, Maps):

const colours = ['red', 'green', 'blue'];

for (const colour of colours) {
  console.log(colour);
}
// → red, green, blue

// Iterating over a string
for (const char of 'hello') {
  console.log(char);
}
// → h, e, l, l, o

Use const for the loop variable in for...of — it is reassigned each iteration but not accumulated.

2.5 break — exit a loop early

// Find the first number divisible by 7
for (let i = 1; i <= 100; i++) {
  if (i % 7 === 0) {
    console.log('Found:', i); // 7
    break; // stop looping immediately
  }
}

// Search array for a value
const names = ['Alice', 'Bob', 'Charlie'];
for (const name of names) {
  if (name === 'Bob') {
    console.log('Found Bob!');
    break;
  }
}

2.6 continue — skip the current iteration

// Print only even numbers
for (let i = 1; i <= 10; i++) {
  if (i % 2 !== 0) continue; // skip odd numbers
  console.log(i); // 2, 4, 6, 8, 10
}

// Skip empty strings
const words = ['hello', '', 'world', '', '!'];
for (const word of words) {
  if (!word) continue; // skip falsy values
  console.log(word);
}
// → hello, world, !

2.7 Nested loops

// Multiplication table
for (let i = 1; i <= 3; i++) {
  for (let j = 1; j <= 3; j++) {
    console.log(`${i} × ${j} = ${i * j}`);
  }
}
// → 1×1=1, 1×2=2, 1×3=3, 2×1=2 ...

// Render a grid of items
const grid = [
  ['a', 'b', 'c'],
  ['d', 'e', 'f'],
];
for (const row of grid) {
  for (const cell of row) {
    process(cell);
  }
}

2.8 Choosing the right loop

LoopBest when
forYou know the exact count, or need the index
whileRepeat until a condition changes (unknown iterations)
do...whileMust run at least once
for...ofIterate over every item in an array or iterable

For working with arrays, you will also use array methods like forEach, map, and filter — covered in Module 12.

3. Real World Example

// Render a product list to the page
const products = [
  { name: 'Laptop',  price: 999,  inStock: true },
  { name: 'Phone',   price: 699,  inStock: false },
  { name: 'Tablet',  price: 499,  inStock: true },
  { name: 'Monitor', price: 399,  inStock: true },
];

const list = document.querySelector('#product-list');

for (const product of products) {
  // Skip out-of-stock items
  if (!product.inStock) continue;

  const li = document.createElement('li');
  li.textContent = `${product.name} — $${product.price}`;
  list.appendChild(li);
}
// Renders: Laptop $999, Tablet $499, Monitor $399 (Phone skipped)

4. Code Example

<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>Loops Demo</title></head>
<body>
  <h1>Loops Demo</h1>
  <button id="run-btn">Run Demos</button>
  <ul id="output"></ul>

  <script>
    function addItem(text) {
      const li = document.createElement('li');
      li.textContent = text;
      document.querySelector('#output').appendChild(li);
    }

    document.querySelector('#run-btn').addEventListener('click', () => {
      document.querySelector('#output').innerHTML = ''; // clear

      // 1. for loop — counting
      addItem('--- for loop ---');
      for (let i = 1; i <= 5; i++) {
        addItem(`Step ${i}`);
      }

      // 2. for...of — iterating an array
      addItem('--- for...of ---');
      const colours = ['red', 'green', 'blue'];
      for (const colour of colours) {
        addItem(`Colour: ${colour}`);
      }

      // 3. while — countdown
      addItem('--- while countdown ---');
      let n = 3;
      while (n > 0) {
        addItem(`T-minus ${n}...`);
        n--;
      }
      addItem('Liftoff!');

      // 4. continue — skip evens
      addItem('--- odd numbers (continue) ---');
      for (let i = 1; i <= 10; i++) {
        if (i % 2 === 0) continue;
        addItem(String(i));
      }

      // 5. break — find first match
      addItem('--- break: first name starting with C ---');
      const names = ['Alice', 'Bob', 'Charlie', 'Diana'];
      for (const name of names) {
        if (name.startsWith('C')) {
          addItem('Found: ' + name);
          break;
        }
      }
    });
  </script>
</body>
</html>

5. Code Breakdown

addItem helper function

A tiny helper that creates a new <li> element and appends it to the #output list. This is a preview of DOM manipulation (Module 10) — for now, understand it as "display this text on the page."

for (let i = 1; i <= 5; i++)

Starting at 1 rather than 0 because we want human-readable "Step 1" through "Step 5". i++ increments after each iteration. The loop stops when i becomes 6 (because 6 <= 5 is false).

for (const colour of colours)

Each iteration, colour is assigned the next element of the array. const is used — there is no reason to re-declare or modify colour, so const communicates that clearly.

while (n > 0) with n--

The loop counts from 3 down to 1. n-- decrements after each iteration. Without n--, the condition n > 0 would never become false — infinite loop.

continue and break

continue jumps back to the top of the loop, skipping the rest of the body for this iteration. break exits the loop entirely. Both are useful for search and filter patterns.

6. Common Mistakes

Mistake 1 — Infinite loop (missing update)

// Bad — i never changes, loop runs forever, freezes the tab
let i = 0;
while (i < 10) {
  console.log(i);
  // forgot i++
}

// Good
while (i < 10) {
  console.log(i);
  i++;
}

Mistake 2 — Off-by-one error

const arr = [1, 2, 3]; // length = 3, indices 0, 1, 2

// Bad — i <= arr.length goes to index 3 (undefined)
for (let i = 0; i <= arr.length; i++) {
  console.log(arr[i]); // last prints 'undefined'
}

// Good — i < arr.length
for (let i = 0; i < arr.length; i++) {
  console.log(arr[i]);
}

Mistake 3 — Modifying an array while looping over it

const nums = [1, 2, 3, 4, 5];
// Bad — skips elements when items are removed mid-loop
for (let i = 0; i < nums.length; i++) {
  if (nums[i] % 2 === 0) nums.splice(i, 1); // length changes
}
// Better: use filter() (Module 12) or loop backwards

Mistake 4 — Using var in for loop (scoping issue)

// Bad — var is function-scoped, not block-scoped
for (var i = 0; i < 3; i++) { ... }
console.log(i); // 3 — i leaks out of the loop!

// Good — let is block-scoped
for (let i = 0; i < 3; i++) { ... }
console.log(i); // ReferenceError — i doesn't exist here

Mistake 5 — Using for...of when you need the index

// for...of doesn't give you the index directly
for (const item of items) {
  console.log(??); // no index available here
}

// Use for with index, or entries()
for (const [index, item] of items.entries()) {
  console.log(index, item);
}
// Or a regular for loop

7. Best Practices

  1. Use for...of for arrays — cleaner and less error-prone than index-based for.
  2. Use let in for loops, not var — block scoping prevents the loop variable from leaking.
  3. Avoid mutating an array while iterating it — use filter() or collect changes and apply after the loop.
  4. Always make sure while conditions can become false — double-check update logic before running.
  5. Prefer array methods (forEach, map, filter, reduce) over manual loops in modern JavaScript — they are more expressive and less error-prone (Module 12).
  6. Limit nesting to 2 levels — deeply nested loops are hard to read; extract inner loops into functions.
  7. Use break early when searching — no need to continue looping after you find what you need.

8. Practice Exercise

  1. Write a for loop that logs the multiplication table for 7 (7×1 through 7×10).
  2. Write a for...of loop that iterates over an array of city names and logs each in uppercase.
  3. Write a while loop that starts at 100 and halves the value each iteration until it is less than 1. Log each step.
  4. Write a loop that builds a string of all even numbers from 2 to 20, separated by commas.
  5. Write a loop that finds the first value in an array of numbers that is greater than 50. Use break once found.

Bonus

  • Generate a 5×5 multiplication table as an HTML <table> element using nested for loops and document.createElement.

9. Assignment

Build a "Number Analyser."

  1. Create an HTML page with a number input and an "Analyse" button.
  2. When the button is clicked, analyse numbers from 1 to the user's entered value:
    • Log all prime numbers in that range. (A prime is only divisible by 1 and itself — use a nested loop or helper function.)
    • Log the sum of all even numbers.
    • Log the sum of all odd numbers.
    • Log the count of numbers divisible by both 3 and 5.
  3. Display results in a summary section on the page (not just the console).
  4. Use at least one break and one continue in your code.

Deliverable: One HTML file with embedded or linked JS.

10. Interview Questions

  1. What is the difference between for and while loops?
    A for loop is used when you know the number of iterations upfront. A while loop is used when you repeat until a condition becomes false, and the number of iterations is unknown.
  2. What does the break keyword do in a loop?
    It immediately exits the loop, skipping all remaining iterations. Used to stop early when a search result is found or a condition is met.
  3. What does the continue keyword do?
    It skips the rest of the current iteration's body and moves to the next iteration. The loop continues — it does not exit.
  4. What is an infinite loop and how do you avoid it?
    An infinite loop runs forever because its condition never becomes false. It freezes the browser tab. Avoid by ensuring the loop variable is updated inside the loop and the condition can eventually evaluate to false.
  5. When would you use for...of instead of a regular for loop?
    When you want to iterate over every item in an array and don't need the index. for...of is cleaner and less error-prone (no off-by-one errors). Use a regular for loop when you need the index or need to loop by a custom increment.
  6. What is an off-by-one error?
    Starting or ending a loop one iteration too early or too late. Common example: using i <= arr.length instead of i < arr.length, which reads one past the end of the array (returns undefined).

11. Additional Resources

  • MDN — for statement
  • MDN — while statement
  • MDN — for...of statement
  • javascript.info — Loops: while and for
  • javascript.info — The for...of loop