Книга: Functional Programming in JavaScript
Назад: Lazy evaluation
Дальше: Callbacks

The functional programmer's toolkit

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 , , and functions, and they are crucial to every functional program of any language. They enable you to remove loops and statements, resulting in cleaner code.

, , and 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 , , , and many more all implement their own , , and methods that are more versatile.

Назад: Lazy evaluation
Дальше: Callbacks

bsn
thank
Vesa Karvonen
I hope you don't mind, but I’d like to point you and your readers to my high-performance optics library for JavaScript that is in production use in multiple projects, has comprehensive support for partial optics and interactive documentation: https://calmm-js.github.io/partial.lenses/ (this takes a moment to load — be patient!)