Lodash _.forEach() method
What you’ll learn
- How
_.forEach(collection, iteratee)walks arrays and objects with a stable callback signature. - Why the method returns the collection and how that enables chaining.
- When to prefer
map/reduceinstead of mutating outer state inside the iteratee. - Try each example in the editor (
?tryit=1,2,3) with Lodash from a CDN.
Prerequisites
Review _.filter() or the collection hub when you need transformed data instead of imperative walks.
- You understand callbacks as
(value, index|key, collection). - You can open Try-it labs or run snippets locally.
Overview
_.forEach is the readable bridge between imperative loops and Lodash pipelines—especially when you must touch Maps-like plain objects or keep fluent chains alive.
Uniform walks
One helper covers indexed lists and keyed dictionaries without branching boilerplate.
Chain-friendly
Returning the collection mirrors fluent APIs even after side-effect steps.
Escape hatch
Return false when continuing would waste work—document the sentinel for teammates.
Syntax
_.forEach(collection, iteratee) - collection: array, array-like, or plain object Lodash can iterate.
- iteratee: invoked as
(value, index|key, collection); returningfalsestops further iteration. - Returns: the original
collectionreference.
Accumulate with an outer binding
Prefer reduce when the aggregation is pure functional style—this pattern shows the imperative accumulator Lodash still enables cleanly.
import forEach from "lodash/forEach";
let total = 0;
forEach([12, 7, 30], (n) => {
total += n;
});
// total → 49 Walk string-keyed objects
Callbacks receive both value and key—ideal for formatting configs or emitting diagnostics.
import forEach from "lodash/forEach";
const lines = [];
forEach({ host: "edge", region: "iad" }, (value, key) => {
lines.push(`${key}=${value}`);
});
lines.join(",");
// → "host=edge,region=iad" Stop early by returning false
Halts remaining visits once a sentinel condition fires—use sparingly and comment why.
import forEach from "lodash/forEach";
const hits = [];
forEach([5, 40, 99, 12], (value) => {
hits.push(value);
if (value > 50) return false;
});
hits;
// → [5, 40, 99] 📋 _.forEach vs map, each, native forEach
| API | Primary goal | Best when |
|---|---|---|
_.forEach(collection, iteratee) | Effects / reads | Uniform iteration across arrays and objects |
_.map(collection, iteratee) | New transformed array | Pure projections without manual pushes |
_.each | Alias of forEach | Legacy code style parity |
array.forEach(fn) | Effects | Arrays only—no object dictionary walks |
Pitfalls to avoid
Non-async friendly
forEach does not await promises—use explicit loops or reduce chains with async orchestration.
Expecting an array
Returning arbitrary values from normal iterations does nothing—switch to map when collecting outputs.
Hidden writes
Mutating shared outer scope can surprise readers—keep callbacks tight or prefer reducers.
❓ FAQ
Summary
- Purpose:
_.forEach(collection, iteratee)visits every element for side effects. - Contrast: reach for
map/reducewhen the deliverable is data, not mutations. - Next: Lodash _.forEachRight(), Lodash _.flatMapDepth() (previous), or collection hub.
Returning false from the iteratee tells Lodash to stop visiting further entries—document that sentinel so teammates do not confuse it with ordinary falsy callback results.
6 people found this page helpful
