Loops are used to execute a block of code repeatedly until a certain condition is met. There are several types of loops in JavaScript, including for
, while
, and do-while
loops. Here’s a brief overview of each with an example:
For Loop
The for loop repeats a block of code a specified number of times.
for (initialization; condition; iteration) {
// code block to be executed
}
Example
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 while a specified condition is true.
while (condition) {
// code block to be executed
}
Example
let i = 0;
while (i < 5) {
console.log(i);
i++;
}
// Output: 0 1 2 3 4
Do While Loop
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.
do {
// code block to be executed
} while (condition);
Example
let i = 0;
do {
console.log(i);
i++;
} while (i < 5);
// Output: 0 1 2 3 4
Each type of loop has its use cases. for loops are commonly used when you know the number of iterations beforehand, while loops are useful when you want to repeat a block of code until a condition becomes false, and do-while loops are handy when you need to execute the block of code at least once before checking the condition.