If you need to stop a loop in the middle of execution, there are two ways: break and continue. Both work from inside an if, but they change the loop's path differently.
const result = [];
for (const num of [1, 2, 3, 4, 5]) {
if (num === 3) {
break; // leaves the loop right here — 4 and 5 never run
}
result.push(num);
}
// result is [1, 2]
const result = [];
for (const num of [1, 2, 3, 4, 5]) {
if (num === 3) {
continue; // skips 3, keeps going
}
result.push(num);
}
// result is [1, 2, 4, 5]
break leaves the whole loop. continue only skips the current lap and moves to the next
one — the loop keeps running.