map(),reduce(),filter()
In simple words, higher order functions in JavaScript can take a function as argument or return a function. map(), reduce() and filter() are higher order built-in functions in ES6 module. One of the advantages of using them is that, it makes code simpler and accelerates workflow.
-
map
It takes an array, call a function on each element in the array and returns a new array. Let’s look at an example.
let nums = [1,2,3,4]; function square(x){ return x*x; } let mappedNums = nums.map(square); console.log(mappedNums); //[1,4,9.16]
The above code can actually be written in one line using arrow syntax.
let nums = [1,2,3,4]; let mappedNums = nums.map(x => x*x); console.log(mappedNums);
-
reduce
This method reduces the array to return a single value. It takes two arguments,
accumulator
andcurrentValue
.accumlator
by default is the first value of the array. So, reduce() loop through each element in an array, perform some function and returns a single value.let nums = [4,11,8,5,9]; let maxNum = nums.reduce((accumalator, currentValue) => { return Math.max(accumalator, currentValue) }) console.log(maxNum);// 11
-
filter It takes an array, checks if each value satisfy a given condition and returns a new array.
let nums = [2,-1,5,16,-20,4,-3]; let newNums = nums.filter(nums => num > 0) console.log(newNums) // [2, 4, 16, 4]