liveBook · Manning

forEach

As explained in Secrets of the JavaScript Ninja, Third Edition

The forEach method is a JavaScript array method that invokes a callback for each assigned element while skipping unassigned index positions.

Need to run the same check on every item in an array? `forEach` calls a callback for each assigned element, skipping unassigned index positions. It offers callback-based iteration without writing a loop. section 10.1.4

Check each value

`const names = ["Yagyu", "Kuma", "Hattori"]; names.forEach((name) => { console.assert(name !== null); });` The callback performs a check for each name; its return value is not used. section 10.1.4

Choose a `for` or `for…of` loop if you need to stop early with `break` or wait between iterations with `await`. `forEach` cannot stop because its callback returns, and an async callback does not make it wait for each promise to settle. It is most handy when reusing a callback across arrays; otherwise, `for…of` is often the simpler choice. section 10.1.4

How Secrets of the JavaScript Ninja, Third Edition covers it

How deep it goes
Explains callback execution, early-exit limits, and async behavior, but does not develop sparse-array examples.
Examples
Checks each name in an array with a console assertion inside a forEach callback.
What it assumes
Assumes familiarity with JavaScript arrays, callbacks, and loops rather than teaching them from zero.
What you can do after
Evaluate/understand when forEach fits array iteration and when early exit or sequential awaiting calls for a loop.
How it connects
Contrasts forEach with for loops, for…of, async callbacks, and other array iteration methods.

Also explained in

Compare how 2 books explain forEach →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Secrets of the JavaScript Ninja, Third Edition. The section links point to the parts of the book it draws on.