In JavaScript, the break
and continue
statements both let you control what's happening inside a loop. But they do very different things. Let's jump right in and look at the differences!
For the following examples, let's assume an array of flavours
for crisps (or "flavors" and "chips" if you're American ):
const flavours = [
"Ready Salted",
"Salt & Vinegar",
"Cheese & Onion"
];
The break
statement
The break
statement completely terminates the loop. After encountering this statement, the loop will not run any further iterations. Control of the script will be returned to the code that comes after the loop.
Given the following code:
for (let i = 0; i < flavours.length; i++) {
// If the current flavour is "Salt & Vinegar", terminate the loop
if (flavours[i] === "Salt & Vinegar") break;
// Log the current flavour
console.log(flavours[i]);
}
Only Ready Salted
will be logged.
This is because when the current flavour becomes Salt & Vinegar
, the break
statement completely terminates the loop.
There will be no further iterations.
The continue
statement
The continue
statement skips the current iteration of the loop. After encountering this statement, the rest of the loop will keep running.
If we change our loop to use the continue
statement:
for (let i = 0; i < flavours.length; i++) {
// If the current flavour is "Salt & Vinegar", skip it
if (flavours[i] === "Salt & Vinegar") continue;
// Log the current flavour
console.log(flavours[i]);
}
Only Ready Salted
and Cheese & Onion
will be logged.
This is because when the current flavour becomes Salt & Vinegar
, the continue
statement skips that iteration only.
The subsequent iterations will still happen.
Summary
- The
break
statement will completely terminate the loop. - The
continue
statement will skip the current iteration only.
I usually default to the Array.forEach()
method for iterating over arrays, but it's important to understand the differences between these statements. The old-school for
and while
loops are still invaluable tools in your arsenal.
If you're not sure whether to use the Array.forEach()
method or a more traditional loop, check out my friend Chris Ferdinandi's article: