Higher-Order Functions

One ugly detail that, if you have any good taste at all, must be starting to bother you is the endlessly repeated for loop going over an array: for (var i = 0; i < something.length; i++) .... Can this be abstracted?

The problem is that, whereas most functions just take some values, combine them, and return something, these for loops contain a piece of code that they must execute. It is easy to write a function that goes over an array and prints out every element:

function printArray(array) {
  for (var i = 0; i < array.length; i++)

But what if we want to do something else than print? Since “doing something” can be represented as a function and since functions are also values, we can pass our action as a function ...

Get Eloquent JavaScript now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.