In JavaScript, loops are used to repeat a block of code multiple times. Here are the different types of loops:
The for loop runs a block of code a set number of times.
for (let i = 0; i < 5; i++) {
console.log(i); // Output: 0, 1, 2, 3, 4
}
Explanation:
let i = 0
: Initializes a variable i
.i < 5
: The condition for the loop to keep running (until i
is less than 5).i++
: Increments i
by 1 after each iteration.The while loop runs as long as a condition is true.
let i = 0;
while (i < 5) {
console.log(i); // Output: 0, 1, 2, 3, 4
i++; // Increment `i` inside the loop
}
Explanation:
i < 5
) is true.i++
: Increments i
inside the loop.The do-while loop is similar to the while
loop, but it guarantees that the block of code will run at least once, even if the condition is false initially.
let i = 0;
do {
console.log(i); // Output: 0, 1, 2, 3, 4
i++;
} while (i < 5);
Explanation: