Functional programming techniques can help in making code easier to understand at a glance and read and test, Functional programming has been making quite a splash in the development world. Functional programming has its special lists of list operations they are exactly like array of things.
The list items are map and reduce. It is important to understand how these functions work for writing clean and functional code which are vastly powerful techniques of functional programming.
1. Map()
The Map() object holds key-value pairs and remembers the original insertion order of the keys. Any value (both objects and primitive values) may be used as either a key or a value.
The Map object iterates elements in the insertion order — for…of loop returns an array of [key, value] for each iteration.
Example:
var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}
Here variable numbers is an array of numbers.
Map() function is used to iterate through the array and return the square root of each element of the array.
Output : 2, 3, 4, 5
2. Reduce()
Reduce() is a method that can be hard to grasp especially with all the complicated explanations that can be found on the internet. There are a lot of benefits to understanding reduce.
The syntax for the reduce array method in JavaScript is:
arr.reduce(callback, initialValue);
Reduce comes with some terminology such as reducer & accumulator and the accumulator is the value that we end with and the reducer is what action we will perform in order to get to one value.
You must remember that a reducer will only return one value and one value only hence the name reduce.
Take the following classic example :
const value = 0;
const array = [5, 10, 15];
for(let i = 0; i < array.length; i++) {
value += array[i];
}
The above code will work fine but using reduce will save us from mutating the value variable.
const initialValue = 0;
const array = [5, 10, 15];
/* reducer method that takes in the accumulator and next item */
const reducer = (accumulator, item) => {
return accumulator + item;
};
/* we give the reduce method our reducer function
and initial value */
const total = array.reduce(reducer, initialValue);
So the first thing we notice is our method is called 3 times because there are 3 values in our array. Our accumulator begins at 0 which is our initialValue we passed to reduce. On each call to the function the item is added to the accumulator. The final call to the method has the accumulator value of 15 and item is 15, 15 + 15 gives us 30 which is our final value. Remember the reducer method returns the accumulator plus the item.