Loop control
Sometimes a loop does not need to run to the end: what you were looking for has been found, or the current item should be skipped. There are two commands for this — break and continue. They work in every loop: for, while and for...of.
break
The break command ends the loop immediately. The program continues with the code that comes after the loop:
for (let i = 1; i <= 10; i++) {
if (i === 4) {
break;
}
console.log(i);
}
// 1
// 2
// 3Although the loop's condition allowed it to reach 10, it stopped at four.
continue
The continue command skips the rest of the current iteration and goes straight to the next one. The loop itself does not stop:
for (let i = 1; i <= 5; i++) {
if (i % 2 === 0) {
continue;
}
console.log(i);
}
// 1
// 3
// 5Even numbers are skipped: console.log does not run for them.
Searching with break
break is most often used when searching: once the item is found, there is no point checking the rest. The result is stored in a variable declared before the loop:
let found = 0;
for (let n = 50; n <= 100; n++) {
if (n % 7 === 0) {
found = n;
break;
}
}
console.log(found); // 56The loop found the first number from 50 that divides by 7 and stopped right away.
Nested loops
A loop can be placed inside another loop — such loops are called nested. For every iteration of the outer loop, the inner loop runs completely:
for (let row = 1; row <= 2; row++) {
for (let col = 1; col <= 3; col++) {
console.log(`${row}-${col}`);
}
}
// 1-1
// 1-2
// 1-3
// 2-1
// 2-2
// 2-3This is how tables, game board cells and all pairs of values are processed.
break in nested loops
break ends only the loop it is written in. The outer loop keeps going afterwards:
for (let row = 1; row <= 2; row++) {
for (let col = 1; col <= 3; col++) {
if (col === 2) {
break;
}
console.log(`${row}-${col}`);
}
}
// 1-1
// 2-1If you need to leave all the loops at once, it is easier to move them into a function and end it with return — more on that in the functions chapter.
Common mistake
In a while loop, continue also jumps over the counter update if it comes further down. The counter stops changing, and the loop becomes infinite:
let i = 0;
while (i < 5) {
if (i === 2) {
continue; // i++ below never runs — the loop hangs
}
i++;
}Update the counter before continue, or use a for loop, where the step always runs.