for-of Supports break, forEach Cannot
for-of honors break and continue to control the loop itself, while return inside forEach only skips one item and the iteration still completes.
Code
const jobs = ['scan', 'prune', 'verify', 'report'];
// for-of 配合 break / continue 控制循环本身
for (const job of jobs) {
if (job === 'prune') continue;
if (job === 'verify') break;
console.log('for-of runs:', job);
}
// forEach 里 return 只跳过当前项:循环无法提前退出
jobs.forEach((job) => {
if (job === 'prune') return;
console.log('forEach runs:', job);
});
// 需要提前退出又能拿到索引时:for-of 配 entries()
for (const [index, job] of jobs.entries()) {
if (job === 'verify') {
console.log('stopped at index', index);
break;
}
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
for-of runs: scan
forEach runs: scan
forEach runs: verify
forEach runs: report
stopped at index 2How the snippet works
The nesting pairs for (const job of jobs) with for (const [index, job] of jobs.entries()) — the inner runs once per outer step.
Top-level bindings jobs hold the demo state — nothing sits inside a function scope.
What to watch for
- The guard
job === 'prune'short-circuits the flow with an earlycontinuewhen its condition holds.
Using it
The demo output is labeled (for-of runs:, forEach runs:, stopped at index), so every printed line maps back to its originating operation.
Key statements
jobs.forEach((job) => {
if (job === 'prune') return;
console.log('forEach runs:', job);
});
Interactive Tools for This Topic
FAQ
- What does the package manager see?
- An empty dependency file. The snippet imports nothing that needs fetching. Its state lives in module-level bindings: `jobs`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.