Technical skill practice
Loop Through a JavaScript Array: Values, Indices and Early Exit
Use a for...of loop when you need array values and direct control over when iteration stops. Add entries when the position matters. An early break belongs to the loop itself; returning from a callback is a different operation.
The task
Read work items in order and stop before processing the blocked item. Preserve its zero-based index in a diagnostic message rather than skipping it and pretending later work was reached.
Runnable Node 22 example
const assert = require('node:assert/strict');
const queue = [{id: 'A', ready: true}, {id: 'B', ready: false}, {id: 'C', ready: true}];
const processed = [];
let blockedAt = -1;
for (const [index, item] of queue.entries()) {
if (!item.ready) { blockedAt = index; break; }
processed.push(`${index}:${item.id}`);
}
assert.deepEqual(processed, ['0:A']);
assert.equal(blockedAt, 1);
assert.equal(queue.length, 3);
console.log(`${processed.join(',')}; blocked=${blockedAt}`);
Expected output and explanation
Only A reaches the processed list. The check for B runs before the append and breaks the surrounding loop, so C is never inspected by the body afterward. Nothing is removed from the source queue.
entries supplies a pair containing an index and value for each visited position. A plain for...of can omit the index when it is unnecessary. Use an indexed for loop if the algorithm specifically needs to adjust its position. for...in enumerates property keys and is not a substitute for this value-and-control task.
Output from the example
0:A; blocked=1
Pitfall to check
Do not use forEach when you need a normal break from traversal. Its callback has separate return behavior. If readiness may change during processing, define whether the loop should use a snapshot or the live state; this fixture has no concurrent updates.
Questions, answered
Is “enumerate” a separate JavaScript array method?
There is no standard Python-style enumerate function built into JavaScript. entries gives index/value pairs for the array loop shown here.
Sources and examples
ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.
Your experience. A complete resume.
Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.
Free account required. Free-plan PDF exports include a watermark.