The continue Statement
The continue statement is the smaller sibling of break. It doesn't end the whole loop, only the current iteration: it skips the rest of the block, and the loop goes straight on to the next iteration.
This loop prints the numbers from 1 to 10, but skips the multiples of 3:
for (let i = 1; i <= 10; i++) {
if (i % 3 === 0) {
continue;
}
console.log(i);
}This prints:
1
2
4
5
7
8
10For 3, 6 and 9, the condition is true, and continue skips the console.log(i) below it. The loop then carries on as usual: the step i++ runs, and the next iteration starts with the next number.
The continue statement usually sits at the beginning of the block and filters out the elements you don't want to deal with: “this one doesn't interest me, on to the next one”. The rest of the block then only handles the interesting ones.
Be careful with continue in a while loop. It jumps straight back to the condition, so if the line that increases the counter is below continue, it is skipped too. The counter then never changes, and the loop never ends. In a for loop, the step always runs, so this can't happen there.
Instructions
- 1
Before going shopping, you want to print only the things you don't have at home. Write a
for...ofloop overshoppingList. At the start of its block, write anifthat skips the item withcontinuewhen theatHomearray includes it. Use.includes(). - 2
After the
if, still inside the loop, printBuy:and the item. The output isBuy: milk,Buy: eggsandBuy: apples, each on its own line.