If you've looked closely at the few examples presented so far, you'll notice a few methods being used that you may not be familiar with. They are the map()
, filter()
, and reduce()
functions, and they are crucial to every functional program of any language. They enable you to remove loops and statements, resulting in cleaner code.
The map()
, filter()
, and reduce()
functions make up the core of the functional programmer's toolkit, a collection of pure, higher-order functions that are the workhorses of the functional method. In fact, they're the epitome of what a pure function and what a higher-order function should be like; they take a function as input and return an output with zero side effects.
While they're standard for browsers that implement ECMAScript 5.1, they only work on arrays. Each time it's called, a new array is created and returned. The existing array is not modified. But there's more, they take functions as inputs, often in the form of anonymous functions referred to as callback functions; they iterate over the array and apply the function to each item in the array!
myArray = [1,2,3,4]; newArray = myArray.map(function(x) {return x*2}); console.log(myArray); // Output: [1,2,3,4] console.log(newArray); // Output: [2,4,6,8]
One more thing. Because they only work on arrays, they do not work on other iterable data structures, like certain objects. Fret not, libraries such as underscore.js
, Lazy.js
, stream.js
, and many more all implement their own map()
, filter()
, and reduce()
methods that are more versatile.