Looping is an important concept in programming. Every language has its own set of predefined looping functions that allows you to iterate over a given set of data. Javascript is no different. Filter, Map, Reduce and Foreach are widely used by javascript programmers. And often end up becoming part of every Javascript interview. Let’s define each of these one by one
ForEach
A for loop accepts a callback and provides current value and current index of the loop as param to this callback. For each iterates through each element of array and calls the callback for each array element. You don’t need to explicitly set a increment decrement counter unlike for loop. This forms the basis of map, filter and reduce.
[1,2,3,4,5].forEach((value, index) => {
console.log(value);
});
OUTPUT:
1
2
3
4
5
Map
Map is an advanced forEach function used to return an alter set of data. For example in the below example we run a map on an array and pass a callback that is increases value by 1. Map will return a new array and save that to newArr which will contain new data with each value increased by 1.
let newArr = [1,2,3,4,5].map((value, index) => value+1);
console.log(newArr)
OUTPUT:
[2,3,4,5,6]
Filter
Filter is used to select a portion of data based on a condition from an array. In the below example we are passing a callback that compares value with 2 if its greater than 2 it returns true else false. Now if the filter function gets true from callback it includes the value in newArr else skips it. Therefore we get a newArr with all elements that are greater than 2.
let newArr = [1,2,3,4,5].filter((value, index) => value>2);
console.log(newArr)
OUTPUT:
[3,4,5]
Reduce
Reduce is the function that most people find confusing. But it is not that complicated. reduce function has something called accumulator this is basically the value returned by callback at the end of execution and is used in next iteration. In below example we are calculating sum of arr which results in 15. What is happening here is initially the accumulator is 0. and we return value + acc = 1 in first iteration similarly in second iteration we get 3 then 6, 10 and finally 15. The initial value of accumulator is passed as second argument after callback. And if no initial value is passed accumulator takes first value of array as initial
let sum = [1,2,3,4,5].reduce((acc, value) => (acc + value), 0);
console.log(sum)
OUTPUT:
15
Hope this is helpful. Feel free to comment if you have doubts. We do provide personalised mentorship you can send an email to learn more about that.
[…] first step to get the shortest string from the array. In order to calculate shortestString we use reduce function instead of while loop or Math.min approach as reduce approach is faster. What we are doing […]