Week 5: Automating Repetitive Tasks with Loops
Learn how to use for, while, and do...while loops in JavaScript to execute code repeatedly.
Explore Chapter 5do...while Loops: Condition Checked After Execution.
The do...while loop is similar to while, but with a key difference: the condition is checked after the loop body executes. This guarantees that the loop body will run at least once, even if the condition is initially false.
Syntax
do {
// Code to execute
// This block runs at least once
statement1;
// Ensure condition might eventually become false
} while (condition);
Example
let attempts = 0;
let password;
do {
// This block runs at least once before checking attempts < 3
password = prompt("Enter password (attempt " + (attempts + 1) + "):");
attempts++;
if (password === null) break; // Handle cancel
} while (password !== "secret" && attempts < 3); // Check condition AFTER the block
if (password === "secret") {
alert("Password accepted!");
} else if(password !== null) {
alert("Too many incorrect attempts.");
} else {
alert("Login cancelled.");
}
do...while is less common than for or while, but useful when you need to guarantee at least one execution of the loop body.
Nested Loops: Loops Inside Loops.
You can place one loop inside another. The inner loop will complete all its iterations for each single iteration of the outer loop.
Example: Creating a Grid Pattern
let rows = 3;
let cols = 4;
for (let i = 0; i < rows; i++) { // Outer loop (for rows)
let rowString = "";
for (let j = 0; j < cols; j++) { // Inner loop (for columns)
rowString += `(${i},${j}) `; // Build up the string for the current row
}
console.log("Row " + i + ": " + rowString);
}
Output:
Row 0: (0,0) (0,1) (0,2) (0,3)
Row 1: (1,0) (1,1) (1,2) (1,3)
Row 2: (2,0) (2,1) (2,2) (2,3)
Nested loops are common for working with multi-dimensional data structures (like grids or matrices) or when you need to perform an operation multiple times for each item in an outer set.