O'Reilly logo

Eloquent JavaScript by Marijn Haverbeke

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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++)
    print(array[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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required