JavaScript Loops - For, While, and Do-While


Loops are essential in JavaScript for repeating a block of code multiple times. In this guide, we'll explore three common types of loops: For, While, and Do-While loops, and provide examples to illustrate each type.


The For Loop


The for loop is often used when you know how many times you want to repeat a block of code:


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

The While Loop


The while loop continues to execute a block of code as long as a specified condition is true:


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 always executes the block of code at least once before checking the condition:


let num = 10;
do {
console.log("Number: " + num);
num--;
} while (num > 0);

Loop Control Statements


Loop control statements like break and continue allow you to modify the behavior of loops:


for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skip iteration when i is 2
}
console.log("Iteration " + i);
}

Nested Loops


You can use loops within loops to create complex patterns or iterate through multi-dimensional arrays:


for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(i + " x " + j + " = " + (i * j));
}
}

Conclusion


Loops are crucial for automating repetitive tasks in JavaScript. By understanding how to use for, while, and do-while loops, as well as loop control statements, you can efficiently handle various programming challenges.


Happy coding!