This article is pointed towards beginners in Javascript or people who are just starting working with functional Javascript and never heard of map, filter and reduce.
What is functional programming?
Functional programming is a programming paradigm where the output value of a function depends only on the arguments that are passed to the function, so calling a function a determinate amount of times will always produce the same result, no matter the amount of times you call it. This contrasts with a lot of common and contemporary code, where a lot of functions work with a local or global state, which may end up returning different results at different executions. A change in that state is a side-effect and, eliminating these, can make it easier to understand and predict the behavior of your code.
Why map, filter, reduce?
One of the key foundations of functional programming is its use of lists and list operations. In Javascript we have map, filter and reduce, all functions that given an initial list (array of things), transform it into something else, while keeping that same original list intact.
Simplify your JavaScript – Use .map(), .reduce(), and .filter()
.map()
Creates a new array by manipulating the values in another array. Great for data manipulation and it is often used in React because it is an immutable method.
Let me explain how it works with a simple example. Say you have received an array containing multiple objects – each one representing a person. The thing you really need in the end, though, is an array containing only the id of each person.
How to use it?
This is the most basic way to call map
Create an array that adds a $ to the beginning of each number.
const numbers = [2, 3, 4, 5];
const dollars = numbers.map( number => '$' + number);
// dollars will be equal to ['$2', '$3', '$4', '$5']
This is the most basic way to call map
As you can see, map receives a callback as an argument. That callback is then given the current value of the iteration, the index of the iteration and the original array from which map was called. There is also an optional second argument for map (after the callback) that is the value to use as “this” inside the callback.