Technical skill practice

JavaScript forEach: Side Effects, Return Values and Callback Scope

Use forEach when you want to perform a callback for the array’s present elements and do not need normal loop control. Its returned value is undefined; a callback return is not a break from the complete traversal.

The task

Build a log for dispatch labels while skipping the paused item’s logging. Record every callback visit separately so a skipped append is not mistaken for stopping the iteration.

Runnable Node 22 example

const assert = require('node:assert/strict');

const labels = ['print', 'pause', 'pack'];
const visited = [];
const log = [];
const result = labels.forEach(label => {
  visited.push(label);
  if (label === 'pause') return;
  log.push(`dispatch:${label}`);
});
assert.equal(result, undefined);
assert.deepEqual(visited, ['print', 'pause', 'pack']);
assert.deepEqual(log, ['dispatch:print', 'dispatch:pack']);
console.log(log.join(' | '));

Expected output and explanation

The callback returns early for pause, so that label is not appended to log. The later pack callback still runs. visited demonstrates that all three positions reached the callback even though only two produced a dispatch entry.

The method result is undefined rather than a collection of callback results. Use map when the task is producing a transformed array, filter when selecting members, and a control loop when later elements must not run after a condition. Those choices express different tasks rather than interchangeable syntax preferences.

Output from the example

dispatch:print | dispatch:pack

Pitfall to check

forEach also does not collect or await the Promises returned by async callbacks. Choose explicit Promise coordination or an awaited loop when completion order matters; a finished forEach call is not proof the asynchronous work finished.

Questions, answered

Can I use continue inside the callback?

A callback is a separate function body. A return can skip the rest of that callback; use an actual loop when you need its continue or break control.

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.