Array.forEach()
iterates its context array and returns nothing. We write the action in the form of a function, or callback. That function is called on each iterated value in the array.
printGrocery()
is the callback function written as a standalone object, making it useful to the whole program, not just this one method call.
Array.forEach(callbackName)
We pass the function name only, without invoking it (pass by reference). The iterator will invoke it using the internal iteration variable as argument, which is represented in the function parameter by element
.
Let’s slip back to a normal for loop to illustrate the abstracted work done by the iterator…
for (let x of array) {
printGrocery(x);
}
The iteration variable x
is the akin to the internal variable to which we earlier alluded.
of
is the membership operator that first appeared in ES2015 and quickly took hold as a useful tool in ES6. It works equally well with strings or arrays.
Let’s translate the standalone back into a callback expression…
groceries.forEach(x => console.log(x));
Now we can extract that expression and make it a standalone…
const printGrocery = x => console.log(x)
and now,
groceries.forEach(printGrocery);
Starting to click?
Having a standalone function that can stand in as a callback and as a utility function to the rest of the program has more bang for the buck Let’s make our standalone into a generic function.
const log = x => console.log(x);
groceries.forEach(log);
anyArray.forEach(log);
log('Math is fun') // Math is fun