When working with loops in JavaScript, it's common to want to skip certain iterations — whether to avoid processing specific values or just to make the logic cleaner.
But not all loop types work the same way when it comes to skipping!
In this blog, we’ll explore:
- ✅ How to skip iterations using
for
loops - ❌ Why
continue
doesn’t work inforEach
- 💡 Workarounds and alternatives
- 🧠 Which loop to choose based on your use case
🧪 1. Skipping Iterations in a for
Loop (The Classic Way)
The continue
statement is your friend here.
for (let i = 0; i < 5; i++) {
if (i === 2) {
continue; // Skip when i is 2
}
console.log(i);
}
🧾 Output:
0
1
3
4
✅ Why it works:
The continue
statement tells the loop to skip the rest of the current iteration and move to the next one.
🚫 2. Why continue
Doesn’t Work in forEach
[1, 2, 3].forEach((num) => {
if (num === 2) {
continue; // ❌ SyntaxError!
}
console.log(num);
});
That’s because forEach
uses a callback function, and continue
is only allowed inside actual loop constructs like for
, while
, or for...of
.
✅ 3. Skipping in forEach
with return
Instead of continue
, you can use return
to skip the current callback execution:
[1, 2, 3, 4].forEach((num) => {
if (num === 3) return; // Skip 3
console.log(num);
});
🧾 Output:
1
2
4
✅ Why it works:
Using return
exits the current callback function early — effectively skipping that iteration.
🔁 4. for...of
— The Flexible Alternative
Need more control (like both continue
and break
)? for...of
is a great middle ground:
const nums = [10, 20, 30, 40];
for (const num of nums) {
if (num === 30) continue;
console.log(num);
}
🧾 Output:
10
20
40
You can also use break
here if needed — which you can’t do with forEach
.
🧠 Which Loop Should You Use?
Use Case | Best Loop |
---|---|
Need break or continue ? |
for , for...of
|
Just iterating over items? |
forEach (if no need to skip/break) |
Transforming data? |
map , filter , reduce
|
Working with async code? |
for...of with await
|
📌 Final Thoughts
Choosing the right loop isn’t just about preference — it’s about control. If you need to skip, short-circuit, or break, prefer for
or for...of
. Use forEach
only when you're sure you'll process every item and don’t need to interrupt the flow.
✍️ Hope this helped clarify one of those subtle gotchas in JavaScript loops!
Great post Abhinav!
Just to add - for...in is another option
It iterates over object keys (or array indices),
You can use both break and continue with for...in loop.
Best used for objects:
`
const obj = {a: 1, b: 2, c: 3, d: 4};
for (const key in obj) {
if (key === 'b') continue; // Skip this iteration
if (key === 'd') break; // Exit the loop
console.log(key, obj[key]);
}
// Output: a 1, c 3
`
So for...in has the same flow control as regular for and for...of loops - unlike forEach which can't use break/continue.