JavaScript forEach(): Side Effects and Return Behavior
Quick answer
forEach() visits present array elements to perform an action. It returns undefined regardless of callback return values.
How it works
The callback receives value, index, source. Ordinary holes are skipped. Initial length bounds iteration; updates to later elements can be observed. A callback return only exits that callback invocation, not the whole traversal. Use an ordinary loop when early break is needed.
const items = [2, 4];const result = items.forEach(n => console.log(n * 3));console.log(result);Expected output in Node.js:
612undefinedLogging is an effect; the method returns undefined.
let count = 0;[1, 2, 3].forEach(n => { if (n === 2) return; count += n; });console.log(count);Expected output in Node.js:
4Returning from the middle callback skips its action but iteration continues.
Common mistakes
ForEach does not collect results or wait for asynchronous callback promises. Use map for transformations; asynchronous sequencing is covered later.
Practice
Trace a forEach callback that logs only positive numbers; compare with filter.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
JavaScript forEach(): Side Effects and Return Behavior — Knowledge Check
Apply the taught concept and predict the output.
What is returned by Array.forEach if callbacks return numbers?
Can an ordinary return inside a forEach callback stop every later invocation?
Which construct is appropriate for a normal early exit from iteration?
What is the exact console output in JavaScript forEach(): Side Effects and Return Behavior example 1?
const items = [2, 4];const result = items.forEach(n => console.log(n * 3));console.log(result);What is the exact console output in JavaScript forEach(): Side Effects and Return Behavior example 2?
let count = 0;[1, 2, 3].forEach(n => { if (n === 2) return; count += n; });console.log(count);