JavaScript Loops

Understanding Loops

Loops are fundamental in JavaScript for executing a block of code multiple times. They are particularly useful when you need to perform repetitive tasks efficiently.

JavaScript supports several types of loops, each with its specific use case:

Choosing the right loop can make your code more efficient and easier to understand. Here are simple examples to illustrate how each loop works:

For Loop Example

This example uses a for loop to print numbers from 0 to 4. The loop initializes a counter at 0, continues until the counter is less than 5, and increments the counter by 1 in each iteration:

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

While Loop Example

This while loop example shows how to execute a block of code as long as a certain condition remains true. Here, the loop starts with a counter at 0 and runs until the counter reaches 5, printing each value:

let i = 0;
    while (i < 5) {
        console.log(i);
        i++;
    }

Do-While Loop Example

The do-while loop is useful for cases where the loop must execute at least once regardless of the condition at the start. This example prints the initial value of the counter and then checks if it should continue:

let i = 0;
    do {
        console.log(i);
        i++;
    } while (i < 5);

Each type of loop offers different advantages depending on your specific programming needs. Understanding these differences is key to leveraging loops effectively in your JavaScript code.

Try it Yourself

Toggle the list of numbers from 1 to 10 and their squares:

Test Your Knowledge: JavaScript Loops

What does a 'for' loop in JavaScript typically require?