JavaScript  

Chapter 5: JavaScript Loops: Repetitive Tasks

Loops allow you to execute a block of code repeatedly until a certain condition is met. They are essential for iterating over collections of data or performing tasks multiple times.

5.1. for loop

The for loop is commonly used when you know the number of iterations beforehand.

  • Syntax

    for (initialization; condition; increment/decrement) {
        // Code to execute repeatedly
    }
  • Example

    for (let i = 0; i < 5; i++) {
        console.log("Count:", i);
    }
    // Output:
    // Count: 0
    // Count: 1
    // Count: 2
    // Count: 3
    // Count: 4

5.2. while loop

The while loop executes a block of code as long as a specified condition is true. Use it when the number of iterations is unknown.

  • Syntax

    while (condition) {
        // Code to execute
        // Make sure to change the condition inside the loop to avoid infinite loops!
    }
  • Example

    let count = 0;
    while (count < 3) {
        console.log("Loop iteration:", count);
        count++; // Increment to eventually make the condition false
    }
    // Output:
    // Loop iteration: 0
    // Loop iteration: 1
    // Loop iteration: 2

5.3. do...while loop

Similar to while, but guarantees the code block executes at least once, as the condition is checked after the first execution.

  • Syntax

    do {
        // Code to execute
    } while (condition);
  • Example

    let i = 0;
    do {
        console.log("Do-While count:", i);
        i++;
    } while (i < 0); // Condition is false, but runs once
    // Output: Do-While count: 0

5.4. break and continue statements

  • break: Terminates the current loop entirely and continues execution after the loop.

    for (let i = 0; i < 10; i++) {
        if (i === 5) {
            break; // Exit loop when i is 5
        }
        console.log(i);
    }
    // Output: 0, 1, 2, 3, 4
  • continue: Skips the current iteration of the loop and proceeds to the next iteration.

    for (let i = 0; i < 5; i++) {
        if (i === 2) {
            continue; // Skip iteration when i is 2
        }
        console.log(i);
    }
    // Output: 0, 1, 3, 4