JavaScript Loops

JavaScript loops are fundamental control structures that allow developers to execute a block of code repeatedly. There are primarily three types of loops in JavaScript: for, while, and do...while. Below, a detailed explanation of each type with examples:

For Loop

The for loop iterates over a range of values using an index variable. It consists of three parts: initialization, condition, and iteration.

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

While Loop

The while loop repeats a block of code as long as a specified condition remains true.

let count = 0; while (count < 3) { console.log(count); // Output: 0, 1, 2 count++; }

Do...While Loop

The do...while loop is similar to the while loop, but it ensures that the loop block is executed at least once before checking the condition.

let num = 5; do { console.log(num); // Output: 5 num--; } while (num > 0);

Loop Control Statements

JavaScript provides loop control statements to modify the loop's behavior:

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

Looping Through Arrays

Loops are commonly used to iterate through arrays:

let colors = ["red", "green", "blue"]; for (let i = 0; i < colors.length; i++) { console.log(colors[i]); // Output: "red", "green", "blue" }

For...of Loop (ES6)

The for...of loop simplifies iterating through arrays and other iterable objects.

let numbers = [1, 2, 3]; for (let num of numbers) { console.log(num); // Output: 1, 2, 3 }

Conclusion

JavaScript loops are essential for automating repetitive tasks, such as iterating through collections, validating conditions, and executing actions multiple times, enhancing the efficiency and functionality of your code.