liveBook · Manning

forEach

As explained in Secrets of the JavaScript Ninja, Second Edition

An Array method that invokes a callback once for each array element.

A `for` loop can visit every array element, but its counter, end condition, and increment add bookkeeping—and places for small bugs to hide. An array’s built-in `forEach` method handles that iteration: provide a callback, and it invokes the callback once for each item. section 9.1.4

Do something with each item

`const weapons = []; ninjas.forEach(ninja => { weapons.push(ninja.weapon); });` visits each ninja and adds its weapon to a separate array. When the goal is specifically to construct a new array from callback results, `map` expresses that job more directly. section 9.1.4

Callbacks also make an important distinction visible: receiving an item as an argument is not the same as using it as the callback’s `this` value. A simplified, hand-built `forEach(list, callback)` demonstrates the latter with `callback.call(list[n], n)`. That example illustrates function context; it is not the built-in array method’s callback pattern. section 4.2.4 section 9.1.4

Listing 4.12. Building a forEach function to demonstrate setting a function context
    function forEach(list, callback) {                                 #A
      for (var n = 0; n < list.length; n++) {
        callback.call(list[n], n);                                     #B
      }
    }

    var weapons = [ { type: 'shuriken' },
                    { type: 'katana' },
                    { type:'nunchucks' }];                             #C

    forEach(weapons, function(index){                                  #D
        assert(this === weapons[index],                                #D
              "Got the expected value of " + weapons[index].type);     #D
    });                                                                #D

Compare this deliberately custom iterator with the built-in method: `call` sets each item as the callback’s context and passes the index as an argument. section 4.2.4

How Secrets of the JavaScript Ninja, Second Edition covers it

How deep it goes
Explains built-in callback iteration through examples, then builds a simplified iterator to demonstrate callback context rather than full method behavior.
Examples
Uses ninja and weapon arrays for item checks and extraction, plus a custom iterator that tests callback context.
What it assumes
Assumes familiarity with arrays and `for` loops while showing an arrow-function callback in use.
What you can do after
Apply it via `Array.prototype.forEach` to visit items without loop bookkeeping, and choose `map` when constructing a new array.
How it connects
Connects array iteration with callbacks, arrow functions, map, and function context set through `call`.

Related concepts

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