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
