8 – Loops (for, while, do-while) (Javascript)

Understanding Loops in JavaScript

Loops are an essential part of JavaScript, allowing you to execute a block of code repeatedly. They are fundamental for automating tasks, iterating through data, and performing operations on collections of items. In JavaScript, you have three primary types of loops: for, while, and do-while.

The ‘for’ Loop

The for loop is a versatile and widely used looping construct. It is especially useful when you know the number of times you want to execute a block of code. The basic structure of a for loop includes an initialization, a condition, and an iteration statement.

Example of a for loop:


    for (let i = 0; i < 5; i++) {
        console.log("Iteration " + i);
    }
The ‘while’ Loop

The while loop is used when you want to repeat a block of code as long as a specified condition is true. The loop continues executing as long as the condition remains true.

Example of a while loop:


    let count = 0;
    while (count < 5) {
        console.log("Count: " + count);
        count++;
    }
The ‘do-while’ Loop

The do-while loop is similar to the while loop, but it guarantees that the code block is executed at least once, even if the condition is false from the start. It checks the condition after executing the code block.

Example of a do-while loop:


    let x = 0;
    do {
        console.log("x: " + x);
        x++;
    } while (x < 5);
Common Use Cases for Loops

Loops are used in various scenarios, including:

  • Iterating Arrays: You can use loops to traverse all elements in an array and perform operations on them.
  • Reading Data: Loops are handy for reading data from external sources like files or APIs.
  • Creating Patterns: You can create patterns or sequences using loops.
  • Repetitive Tasks: Any task that needs to be repeated a specific number of times or until a condition is met.
Loop Control Statements

JavaScript provides loop control statements that allow you to modify the flow of loops:

  • break: Exits the loop prematurely, regardless of whether the loop condition is met.
  • continue: Skips the current iteration and proceeds to the next iteration of the loop.

Example of break and continue:


    for (let i = 0; i < 10; i++) {
        if (i === 5) {
            break; // Exit the loop when i equals 5
        }
        if (i % 2 === 0) {
            continue; // Skip even numbers
        }
        console.log("Value of i: " + i);
    }
Conclusion

Loops are a fundamental aspect of JavaScript that enables the automation of repetitive tasks and the iteration through data. Understanding when and how to use for, while, and do-while loops, as well as loop control statements, is essential for any JavaScript developer. These concepts empower you to write efficient and flexible code that can handle a wide range of scenarios.