You are previewing Eloquent JavaScript.

Eloquent JavaScript

Cover of Eloquent JavaScript by Marijn Haverbeke Published by No Starch Press

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 ...

The best content for your career. Discover unlimited learning on demand for around $1/day.