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 5

Chapter 5: Repeating Actions with for, while, and do...while Loops

for Loops: Iterating a Specific Number of Times or Over Iterables.

The for loop is commonly used when you know in advance how many times you want to repeat a block of code or when you want to iterate over the elements of an iterable (like an array or string).

Classic for Loop Syntax

for (initialization; condition; final-expression) {
  // Code to be executed in each iteration
  statement1;
  statement2;
  // ...
}
  • initialization: Executed once before the loop starts. Often used to declare and initialize a loop counter (e.g., let i = 0).
  • condition: Evaluated before each iteration. If it's true, the loop body executes. If it's false, the loop terminates.
  • final-expression: Executed at the end of each iteration, typically used to increment or decrement the loop counter (e.g., i++, i--).

Example: Counting 0 to 4

for (let i = 0; i < 5; i++) {
  console.log("The number is " + i);
}

Output:

The number is 0
The number is 1
The number is 2
The number is 3
The number is 4

Iterating Over Strings (using classic for loop)

let message = "Hello";
for (let i = 0; i < message.length; i++) {
  console.log("Character at index " + i + ": " + message[i]);
}

Other for Loop Variants (Brief Mention - More with Arrays/Objects)

JavaScript also has other for loop variants designed specifically for iterating over collections:

  • for...in: Iterates over the *property names* (keys) of an object.
  • for...of: Iterates over the *values* of an iterable object (like arrays, strings, maps, sets).

We will explore for...in and for...of more when we cover Objects and Arrays in detail.

while Loops: Repeating Actions Based on a Condition.

A while loop executes a block of code repeatedly as long as a specified condition remains true.

Syntax

while (condition) {
  // Code to execute as long as condition is true
  statement1;
  // IMPORTANT: Ensure the condition eventually becomes false!
}
  • The condition is evaluated before each iteration.
  • If the condition is true, the loop body executes.
  • If the condition is initially false, the loop body never executes.
  • You must include logic within the loop to eventually make the condition false, otherwise, you'll create an infinite loop.

Example: Countdown

let count = 3;
while (count > 0) {
  console.log(count + "...");
  count--; // Decrement count, crucial to eventually exit the loop
}
console.log("Blast off!");

Output:

3...
2...
1...
Blast off!

Example: Guessing Game (Simple)

let correctNumber = 7;
let guess = 0; // Initialize guess

while (guess !== correctNumber) {
  // In a real app, get input differently, prompt halts execution
  let guessStr = prompt("Guess the number (1-10):");
  if (guessStr === null) break; // Handle cancel button

  guess = parseInt(guessStr); // Convert string input to number

  if (guess !== correctNumber) {
    alert("Wrong guess, try again!");
  }
}

if (guess === correctNumber) { // Check if loop exited due to correct guess
    alert("You guessed it! The number was " + correctNumber);
} else {
    alert("You gave up!");
}

do...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.

break and continue: Controlling Loop Flow.

These statements allow you to alter the normal execution flow within loops (for, while, do...while).

break Statement

The break statement immediately terminates the innermost loop it's contained within. Program execution continues with the statement immediately following the terminated loop.

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    console.log("Found 5! Breaking loop.");
    break; // Exit the loop immediately
  }
  console.log("Current number:", i);
}
console.log("Loop finished.");

Output:

Current number: 0
Current number: 1
Current number: 2
Current number: 3
Current number: 4
Found 5! Breaking loop.
Loop finished.

continue Statement

The continue statement skips the rest of the current iteration of the loop and proceeds immediately to the next iteration (checking the condition again in while/do...while, or executing the final-expression in for).

for (let i = 1; i <= 5; i++) {
  if (i % 2 !== 0) { // If the number is odd
    continue; // Skip the rest of this iteration
  }
  // This line only runs for even numbers
  console.log("Found an even number:", i);
}

Output:

Found an even number: 2
Found an even number: 4

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.

Syllabus