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 ...
Get Eloquent JavaScript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.