Autocodewizard Logo Loops in JavaScript - Autocodewizard Ebooks - JavaScript Essentials: From Fundamentals to Advanced Techniques

Chapter 5: Loops in JavaScript

Learn about loops in JavaScript, including for, while, and do...while loops, to automate repetitive tasks effectively.

In this chapter, we’ll explore different types of loops in JavaScript. Loops allow you to run a block of code multiple times, making it easier to automate repetitive tasks and handle collections of data.

The for Loop

The for loop is commonly used when the number of iterations is known. It has three main parts: initialization, condition, and increment.

// Example: for loop
for (let i = 0; i < 5; i++) {
    console.log("Iteration:", i);
}

In this example, the loop starts with i = 0 and continues as long as i < 5. After each iteration, i increments by 1. This prints "Iteration: 0" through "Iteration: 4".

The while Loop

The while loop runs as long as a specified condition is true. It’s useful when the number of iterations is not known ahead of time.

// Example: while loop
let count = 0;

while (count < 5) {
    console.log("Count is:", count);
    count++;
}

In this example, the loop runs as long as count < 5. The count++ increments count by 1 each time, stopping the loop when count reaches 5.

The do...while Loop

The do...while loop is similar to the while loop, but it guarantees at least one execution of the code block, as the condition is evaluated after each iteration.

// Example: do...while loop
let number = 0;

do {
    console.log("Number is:", number);
    number++;
} while (number < 5);

In this example, do...while prints "Number is: 0" through "Number is: 4". The loop checks the condition number < 5 after each iteration, so the code runs at least once even if number starts out at 5.

Looping Through Arrays

Loops are often used to iterate over arrays, making it easy to access each element in a collection:

// Example: for loop with an array
let fruits = ["apple", "banana", "cherry"];

for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

This example iterates through the fruits array, printing each element. fruits.length gives the total number of items in the array, ensuring the loop accesses each item exactly once.

The for...of Loop

The for...of loop is a simpler way to iterate over arrays and other iterable objects. It retrieves each element directly, without needing an index.

// Example: for...of loop
for (let fruit of fruits) {
    console.log(fruit);
}

In this example, for...of iterates through each element in fruits and prints it. This loop is especially useful for readable and concise code.

Breaking Out of Loops

Use the break statement to exit a loop prematurely when a specific condition is met:

// Example: break statement
for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;
    }
    console.log(i);
}

This example stops the loop once i reaches 5, so only the numbers 0 to 4 are printed.

Continuing to the Next Iteration

Use the continue statement to skip the current iteration and proceed to the next one:

// Example: continue statement
for (let i = 0; i < 10; i++) {
    if (i % 2 === 0) {
        continue;
    }
    console.log(i);  // Outputs only odd numbers
}

This example uses continue to skip even numbers, so only odd numbers are printed.

Summary and Next Steps

In this chapter, we covered the main types of loops in JavaScript: for, while, do...while, and for...of loops, along with ways to break out of or continue within loops. Loops are essential for automating repetitive tasks and handling data collections efficiently. In the next chapter, we’ll learn about functions and modularizing code for reusability and organization.