The for
Loop:
The for
loop is used when you know the number of iterations in advance. It consists of three parts: initialization, condition, and iteration expression.
for (let i = 0; i < 5; i++) {
console.log(i);
}
This will print numbers from 0
to 4
. The loop starts by initializing i
to 0, checks if i
is less than 5, and increments i
by 1 after each iteration.
Use Case:
Use a for
loop when you know the exact number of iterations, such as iterating over an array or performing a task a set number of times.
The while
Loop:
A while
loop is useful when you want to repeat a task an unknown number of times but want to ensure that a condition is checked before each iteration.
let counter = 0;
while (counter < 5) {
console.log(counter);
counter++;
}
The loop continues as long as the condition (counter < 5
) is true. In this case, it prints numbers from 0 to 4.
Use Case:
Use a while
loop when the number of iterations is not known beforehand, and you need to loop as long as a certain condition holds true.
The do-while
Loop:
let counter = 0;
do {
console.log(counter);
counter++;
} while (counter < 5);
This loop will behave the same as the while
loop in this case, printing numbers from 0 to 4. However, if the condition were initially false, the do-while
loop would still execute once before checking the condition.
Use Case:
Use a do-while
loop when you need to ensure that the code inside the loop is executed at least once, even if the condition is false at the start.