Apply JavaScript loops (for, while, do-while)

21 Programming for the Web

Objective – Apply JavaScript loops (for, while, do‑while) and related control structures


0. Foundations – the building blocks you need before looping

  • Variables & declaration
    • let – block‑scoped, can be reassigned.
    • const – block‑scoped, cannot be reassigned.
    • var – function‑scoped (kept for legacy code only).
  • Primitive data types
    • Number, String, Boolean, null, undefined
  • Objects & arrays
    // array
    let colours = ["red", "green", "blue"];
    
    // object
    let person = {
        name: "Alice",
        age: 17
    };
    
  • Operators
    • Arithmetic: +, -, *, /, %
    • Comparison: ===, !==, <, >, <=, >=
    • Logical: &&, ||, !
    • Assignment: =, +=, -=, …
  • Functions
    function greet(name) {
        return "Hello, " + name + "!";
    }
    console.log(greet("Bob"));
    
  • Error handling (try … catch)
    try {
        let n = Number(prompt("Enter a number"));
        if (isNaN(n)) throw new Error("Not a number");
        console.log("You entered", n);
    } catch (e) {
        console.error("Error:", e.message);
    }
    

1. Loop concepts – why and when we use them

  • Purpose – repeat a block of statements without rewriting the same code.
  • Three fundamental iteration structures
    • for – countable repetitions; initialise, test, update are all visible.
    • while – repeat while a condition remains true; the condition is tested before each iteration.
    • do‑while – same as while but the body is executed at least once because the test comes after the body.

2. Loop syntax (JavaScript)

Loop type General form Typical use‑case
for
for (initialisation; condition; increment) {
    // statements
}
Counting, iterating over arrays, fixed‑repetition tasks.
while
while (condition) {
    // statements
    // optional update
}
Repeating until a sentinel value or user action stops the loop.
do‑while
do {
    // statements
    // optional update
} while (condition);
Menu systems, input prompts that must appear at least once.

3. Translating algorithmic notation → flow‑chart → JavaScript

The Cambridge syllabus expects you to move freely between pseudocode, flow‑charts (using the standard symbols) and actual JavaScript code. The three examples below each contain:

  1. Pseudocode (syllabus symbols).
  2. A full‑size flow‑chart (image placeholder – draw or copy the diagram into your notebook).
  3. Working JavaScript.

3.1 Counting from 1 to 5 – for loop

Pseudocode

FOR i ← 1 TO 5 DO
    OUTPUT i
ENDFOR

Flow‑chart

Flow‑chart for a FOR loop (initialise i, test i≤5, output, increment i, back to test)
Start → Initialise i=1 → Test i≤5? → Yes → Output i → i←i+1 → Back to Test → No → End

JavaScript

for (let i = 1; i <= 5; i++) {
    console.log(i);
}

3.2 Summing numbers entered by the user – while loop

Pseudocode

SET total ← 0
REPEAT
    INPUT input "Enter a number (Cancel to stop):"
    IF input ≠ NULL THEN
        SET total ← total + NUMERIC(input)
    ENDIF
UNTIL input = NULL
OUTPUT "Total =", total

Flow‑chart

Flow‑chart for a WHILE loop (total←0, input, decision input=null?, add to total, back to input)
Start → total←0 → Input → Decision (input=null?) → No → total←total+input → Back to Input → Yes → Output total → End

JavaScript

let total = 0;
let input = prompt("Enter a number (Cancel to stop):");
while (input !== null) {
    total += Number(input);
    input = prompt("Enter a number (Cancel to stop):");
}
console.log("Total =", total);

3.3 Simple menu – do‑while loop

Pseudocode

REPEAT
    INPUT choice "Menu:1. Add2. Subtract3. Exit"
    SELECT choice
        CASE "1": OUTPUT "Add selected"
        CASE "2": OUTPUT "Subtract selected"
        CASE OTHERWISE: /* do nothing */
    ENDSELECT
UNTIL choice = "3"

Flow‑chart

Flow‑chart for a DO‑WHILE loop (display menu, input, switch, decision choice='3'?, back to menu)
Start → Display menu → Input choice → Switch → Decision (choice='3'?) → No → Back to menu → Yes → End

JavaScript

let choice;
do {
    choice = prompt("Menu:1. Add2. Subtract3. Exit");
    switch (choice) {
        case "1":
            console.log("Add selected");
            break;
        case "2":
            console.log("Subtract selected");
            break;
    }
} while (choice !== "3");

4. Loop‑control statements and selection inside loops

  • break – exits the nearest enclosing loop immediately.
  • continue – skips the remainder of the current iteration and proceeds with the next iteration.
  • return – ends the whole function (also terminates any loops inside that function).
  • if … else – single‑branch or multi‑branch selection.
  • switch … case – convenient when a variable can take several discrete values.
  • try … catch – handles run‑time errors without crashing the script.

4.1 break example – stop when the user types “ESC”

while (true) {
    let key = prompt("Press a key (type ESC to stop):");
    if (key === "ESC") {
        break;               // exit the loop
    }
    console.log("You pressed:", key);
}

4.2 continue example – skip odd numbers

for (let i = 1; i <= 10; i++) {
    if (i % 2 !== 0) {
        continue;           // skip the rest of this iteration
    }
    console.log(i);          // only even numbers are printed
}

4.3 if … else inside a while loop

let n = 1;
while (n <= 20) {
    if (n % 3 === 0) {
        console.log(n + " is divisible by 3");
    } else {
        console.log(n + " is not divisible by 3");
    }
    n++;
}

4.4 Exception handling inside a loop

while (true) {
    try {
        let val = Number(prompt("Enter a positive integer (Cancel to quit):"));
        if (isNaN(val) || val < 0) throw new Error("Invalid input");
        console.log("You entered", val);
    } catch (e) {
        console.error(e.message);
    }
    if (val === null) break;
}

5. Nested loops and combined selection

5.1 Multiplication table – for inside for

for (let i = 1; i <= 10; i++) {          // rows
    let row = "";
    for (let j = 1; j <= 10; j++) {      // columns
        row += (i * j).toString().padStart(4, " ");
    }
    console.log(row);
}

Pseudocode

FOR i ← 1 TO 10 DO
    SET row ← ""
    FOR j ← 1 TO 10 DO
        SET row ← row + (i*j)
    ENDFOR
    OUTPUT row
ENDFOR

5.2 if inside a while loop – find numbers divisible by 3

let n = 1;
while (n <= 20) {
    if (n % 3 === 0) {
        console.log(n + " is divisible by 3");
    }
    n++;
}

6. Common pitfalls (and how to avoid them)

  1. Infinite loops – the condition never becomes false.
    • Fix: ensure the loop variable is updated, or use break when a termination condition is met.
  2. Off‑by‑one errors – using < when you need <= (or vice‑versa).
    • Tip: draw a quick table of start, end and expected number of iterations.
  3. Changing the loop variable inside the body – can cause jumps or missed iterations.
    • Keep the increment/decrement in the loop header whenever possible.
  4. Variable scope
    • let / const are block‑scoped – they disappear after the loop.
    • var is function‑scoped – the variable remains accessible after the loop, which can lead to bugs.
    // var – function scope (may cause bugs)
    for (var i = 0; i < 3; i++) {
        // …
    }
    console.log(i);   // 3 (still accessible)
    
    // let – block scope (safer)
    for (let j = 0; j < 3; j++) {
        // …
    }
    console.log(j);   // ReferenceError: j is not defined
    

7. Testing & debugging of loop‑based programs

  • Dry‑run on paper – write down the initial values, then step through each iteration, updating variables as you go.
  • Console logging – insert console.log() statements to display the loop variable and any intermediate results.
  • Break‑point debugging – use the browser’s developer tools (e.g., Chrome DevTools) to pause execution at the start of the loop and step through each iteration.
  • Boundary testing – test the loop with the smallest, typical and largest expected inputs (e.g., 0, 1, 10, 100).
  • Check for side‑effects – ensure that variables modified inside the loop are intended and that no unintended global variables are created.

8. Practical application – Sum of the first n natural numbers

Mathematically: S = n(n + 1) / 2. The iterative version demonstrates a for loop.

Pseudocode

SET sum ← 0
FOR i ← 1 TO n DO
    SET sum ← sum + i
ENDFOR
OUTPUT sum

JavaScript

function sumNaturalNumbers(n) {
    let sum = 0;
    for (let i = 1; i <= n; i++) {
        sum += i;
    }
    return sum;
}
console.log(sumNaturalNumbers(10)); // 55

9. Web‑specific programming with loops

In the Cambridge A‑Level “Programming for the Web” you must show how loops are used **inside a web page**. The following short examples illustrate the most common scenarios.

9.1 Updating the DOM inside a for loop

<ul id="list"></ul>

<script>
const ul = document.getElementById("list");
for (let i = 1; i <= 5; i++) {
    const li = document.createElement("li");
    li.textContent = "Item " + i;
    ul.appendChild(li);
}
</script>

9.2 Event‑driven while loop (simulated with setInterval)

<button id="stopBtn">Stop counting</button>
<div id="counter">0</div>

<script>
let count = 0;
const counterDiv = document.getElementById("counter");
const timer = setInterval(() => {
    count++;
    counterDiv.textContent = count;
    if (count >= 20) clearInterval(timer);   // manual break condition
}, 500);

document.getElementById("stopBtn").addEventListener("click", () => {
    clearInterval(timer);                     // stop the loop early
});
</script>

9.3 Form validation with a do‑while loop

<form id="loginForm">
    Password: <input type="password" id="pwd">
    <button type="submit">Login</button>
</form>
<script>
const form = document.getElementById("loginForm");
form.addEventListener("submit", function (e) {
    e.preventDefault();                       // stop normal submission
    let ok = false;
    do {
        const pwd = document.getElementById("pwd").value;
        if (pwd === "Cambridge2025") {
            alert("Access granted");
            ok = true;
        } else {
            alert("Wrong password – try again");
        }
    } while (!ok);
});
</script>

9.4 Fetching data with a loop (asynchronous for…of example)

<script>
async function loadPosts(ids) {
    for (const id of ids) {                     // loop over an array
        const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${id}`);
        const post = await response.json();
        console.log(`Post ${id}:`, post.title);
    }
}
loadPosts([1, 2, 3, 4, 5]);
</script>

10. Exercise questions

  1. Write a while loop that prints the multiplication table of 7 (from 7 × 1 up to 7 × 10).
  2. Using a do‑while loop, create a simple password‑check that continues to ask the user for a password until the correct one (“Cambridge2025”) is entered.
  3. Given let colours = ["red","green","blue","yellow"];, rewrite the following for loop as a while loop:
    for (let i = 0; i < colours.length; i++) {
        console.log(colours[i]);
    }
  4. Explain why the following code results in an infinite loop and correct it:
    let i = 0;
    while (i < 5) {
        console.log(i);
    }
  5. Demonstrate the use of break and continue inside a loop that iterates from 1 to 20, printing only the numbers that are multiples of 4 but stopping completely when the number 16 is reached.
  6. Identify the scope error in this snippet and fix it:
    for (var i = 1; i <= 3; i++) {
        setTimeout(() => console.log(i), 100);
    }
  7. Write a short script that uses a for loop to create a list of items in the DOM (see example 9.1) and then adds a click‑handler to each item that alerts its position in the list.
  8. Using fetch and an asynchronous for…of loop, retrieve the titles of the first three posts from https://jsonplaceholder.typicode.com/posts and display them in a paragraph element.

11. Suggested diagram – Flow‑chart comparison of for, while and do‑while

Three side‑by‑side flow‑charts showing the order of execution for FOR, WHILE and DO‑WHILE loops
Each diagram uses the Cambridge symbols: rectangle (process), diamond (decision), arrow (flow). Note where the test occurs – before the body for for and while, after the body for do‑while.

Create an account or Login to take a Quiz

43 views
0 improvement suggestions

Log in to suggest improvements to this note.