Higher-order Functions

Think of the number of times that you've processed an array with a loop. Maybe you wanted to print each element, so you wrote code like this:

for (let i = 0; i < items.length; ++i) {

Maybe you wanted to hide all the elements stored in the array:

for (let i = 0; i < elements.length; ++i) {
elements[i].style.display = 'none';

Both of these algorithms follow the same overall pattern:

for each item in items
process the item

The only thing that changes is how each item is processed. Since this pattern of looping and processing elements is so common, it has been abstracted into the forEach method of the Array class. Since the method doesn't know what processing needs to be done, it expects you to pass in a function that processes a single item. The function that you pass could be a named function, a function literal, or an arrow function.

Arrow functions shorten the code considerably:

items.forEach(item => console.log(item));
elements.forEach(element => element.style.display = 'none');

The index of each element is passed as the second parameter to your parameter function, should you need it:

items.forEach((item, i) => console.log(i, '->', item));

Functions that receive other functions as parameters are called higher-order functions. They are found all over JavaScript. The forEach method is one of several higher-order functions commonly found in modern programming languages that provide abstractions for looping through an array.