continue
Skips the rest of the current loop turn and moves straight to the next one.
Example
#const students = [
{ name: 'Emma', paid: true },
{ name: 'Jack', paid: false },
{ name: 'Mia', paid: true }
]
for (const student of students) {
if (!student.paid) continue
console.log(`Access for: ${student.name}`)
}Definition and usage
#The continue statement ends only the current loop turn. The code below it is skipped, and the loop moves on to the next iteration. In for, the step, e.g. i++, still runs first, while in while and do...while the condition is checked right away.
It lets you reject elements that don’t match right at the top of the loop, instead of wrapping the rest of the code in a big if. It’s the same idea as an early return in a function.
Like break, it only works in loops, and with a label (continue outer) it jumps to the next turn of the outer loop. Inside a forEach() callback, its equivalent is return.
Syntax
#continue
continue labelMore examples
#const odd = []
for (let i = 1; i <= 10; i++) {
if (i % 2 === 0) continue
odd.push(i)
}
console.log(odd)let i = 0
const kept = []
while (i < 5) {
i++
if (i === 3) continue
kept.push(i)
}
console.log(kept)The counter is incremented before continue. If i++ were at the end of the loop, continue would skip past it and the loop would never finish.
Browser support
#Widely available
Works in all modern browsers, phones included. You can use it without worry.
- Chrome
- Edge
- Firefox
- Safari
Good practices
#- In
while, change the counter beforecontinue, otherwise the loop may never end. - If the whole loop only picks out elements,
filter()says it more concisely:students.filter((student) => student.paid).
Related entries
#- breakImmediately ends a loop or a switch statement and moves on to the code right after it.
- forA loop with a counter: initialization, condition, and step. Repeats a block of code while the condition is true.
- for...ofWalks the successive values of an iterable object: an array, a string, a Map, a Set, and others.
- whileRepeats a block of code while the condition is true. The condition is checked before every turn.
- Array.prototype.filter()Creates a new array with the elements for which the function returned true.
Spotted a mistake or missing an example? Write to us.