Day 10 of 21 Days of Javascript
Today I covered more higher order functions. Map and reduce. Yesterday I covered filter. One of the benefits of using these functions is composability. This is the idea of using relatively small blocks of code chained together for more complex behaviour.
Here's a quick example. If we have a list of numbers [1, 2, 3, 4] and we want to transform each number by firstly, adding 2 to it. We then want to filter the list to just odd numbers. Here's how you might write that with just one block of code:
let myList = [1, 2, 3, 4];
const result = [];
let new_num;
for (let num of myList) {
new_num = num + 2; // add 2 to each number
if (new_num % 2 !== 0) { // check if it’s odd
result.push(new_num); // add to results list if its odd
}
}
console.log(result); // will print [3, 5]
That code works fine. But we could use Javascript's built-in higher order functions and do the following with just one line:
let result = myList.map(n => n + 2).filter(n => n % 2 !== 0)
Here we are using composability. That is, we have two higher-order functions (map and filter) working on our inputs. See the full code example below.
let myList = [1, 2, 3, 4];
const result = [];
let result = myList.map(n => n + 2).filter(n => n % 2 !== 0);
console.log(result); // will print [3, 5]