JavaScript Loops: Comprehensive Guide
Loops in JavaScript are used when you want to repeat a block of code multiple times until a certain
condition is met. This guide explains for, while, break, and continue with examples.
1. for loop
A for loop is best when you know in advance how many times you want to repeat something.
for (let i = 1; i <= 5; i++) {
[Link](i);
}
Output: 1, 2, 3, 4, 5
2. while loop
A while loop is useful when you don’t know in advance how many times the code should run.
let i = 1;
while (i <= 5) {
[Link](i);
i++;
}
Output: 1, 2, 3, 4, 5
3. break in loops
The break statement is used to stop a loop immediately.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
break;
}
[Link](i);
}
Output: 1, 2
4. continue in loops
The continue statement skips the current iteration and jumps to the next one.
for (let i = 1; i <= 5; i++) {
if (i === 3) {
continue;
}
[Link](i);
}
Output: 1, 2, 4, 5
Summary
for loop → best when you know how many times to loop. while loop → best when iterations are
unknown, runs until condition is false. break → immediately exits the loop. continue → skips
current iteration, continues with the next.