for, while, do‑while) and related control structureslet – block‑scoped, can be reassigned.const – block‑scoped, cannot be reassigned.var – function‑scoped (kept for legacy code only).null, undefined// array
let colours = ["red", "green", "blue"];
// object
let person = {
name: "Alice",
age: 17
};
+, -, *, /, %===, !==, <, >, <=, >=&&, ||, !=, +=, -=, …function greet(name) {
return "Hello, " + name + "!";
}
console.log(greet("Bob"));
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);
}
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.| Loop type | General form | Typical use‑case |
|---|---|---|
for |
|
Counting, iterating over arrays, fixed‑repetition tasks. |
while |
|
Repeating until a sentinel value or user action stops the loop. |
do‑while |
|
Menu systems, input prompts that must appear at least once. |
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:
for loopPseudocode
FOR i ← 1 TO 5 DO
OUTPUT i
ENDFOR
Flow‑chart
JavaScript
for (let i = 1; i <= 5; i++) {
console.log(i);
}
while loopPseudocode
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
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);
do‑while loopPseudocode
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
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");
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.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);
}
continue example – skip odd numbersfor (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
}
if … else inside a while looplet 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++;
}
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;
}
for inside forfor (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
if inside a while loop – find numbers divisible by 3let n = 1;
while (n <= 20) {
if (n % 3 === 0) {
console.log(n + " is divisible by 3");
}
n++;
}
break when a termination condition is met.< when you need <= (or vice‑versa).
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
console.log() statements to display the loop variable and any intermediate results.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
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.
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>
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>
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>
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>
while loop that prints the multiplication table of 7 (from 7 × 1 up to 7 × 10).do‑while loop, create a simple password‑check that continues to ask the user for a password until the correct one (“Cambridge2025”) is entered.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]);
}
let i = 0;
while (i < 5) {
console.log(i);
}
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.for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log(i), 100);
}
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.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.for, while and do‑while
for and while, after the body for do‑while.Create an account or Login to take a Quiz
Log in to suggest improvements to this note.
Your generous donation helps us continue providing free Cambridge IGCSE & A-Level resources, past papers, syllabus notes, revision questions, and high-quality online tutoring to students across Kenya.