This will log up to Variable 'i' is 5, and then end the loop early when it runs the break
statement. You can use break
in both 'for' and 'while' loops.
Infinite loops
It's possible to set up a loop with a condition that is always true, so it's set to repeat the loop body forever. This can be done with while (true)
or for (;;)
(where all three parts of the 'for' loop are left empty: no variable declared, no condition, and no step).
Then the only way to end the loop is with the break
statement. This must be run at some point, otherwise the loop will never end. This is one possible cause of software 'hanging', i.e. freezing and stopping responding - it's stuck in an endless loop and never gets the chance to respond to further inputs.
Here's an example of a supposedly infinite loop that uses break
to end it.
let i = 0;
while (true)
{
console.log(`Variable 'i' is ${i}`);
i++;
if (i === 5)
break; // end infinite loop
}
This is equivalent to using a 'for' loop to repeat a certain number of times. However this approach of writing an infinite loop that's ended with break
can be useful in more complex situations where you don't actually know in advance how many iterations need to be run, so it's useful to be aware of the approach.
Continue
The continue
statement ends the loop body early, but continues running the loop. Each run of the loop is called an iteration, so another way of putting this is it cancels the current iteration and skips to the next iteration. Try the following code sample.
for (let i = 0; i < 10; i++)
{
if (i === 5)
continue; // skip logging message
console.log(`Variable 'i' is ${i}`);
}
This logs every value of i
from 0 to 9, but skips 5. This is because when i
is 5, it runs the continue
statement, which skips ahead to the next iteration where i
is 6. You can use continue
in both 'for' and 'while' loops.