fbpx

Map() Vs forEach() in javascript

Are you confuse between map() and forEach(). Many times you face this question interview but you are unable to explain it better way. Let clear this concept in depth.

forEach():

Whenever we want to traverse the array, the first thing that comes in our mind is normal for loop. Like other language javascript also provide many alternatives to traversing the array one of them is forEach. Let discuss the key feature of this.

#1: forEach() calls a provided callback function once for each element in an array in ascending order. 

const array1 = ['a', 'b', 'c'];

array1.forEach((item, index) => console.log(item, index));

// expected output: "a" 0
// expected output: "b" 1
// expected output: "c" 2

arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);

syntax of forEach

the callback is invoked with three arguments:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

#2: thisArg: If passing the function argument using an arrow function expression the thisArg parameter can be omitted as arrow functions lexically bind this value.

function Counter() {
  this.sum = 0;
  this.count = 0;
}
Counter.prototype.add = function(array) {
  array.forEach(function(entry) {
    this.sum += entry;
    ++this.count;
  }, this);
  // ^---- Note
};

const obj = new Counter();
obj.add([2, 5, 9]);
obj.count;
// 3 
obj.sum;
// 16

Since the thisArg parameter (this) is provided to forEach(), it is passed to callback each time it’s invoked, for use as its this value.

In short, if we want the current instance of the object in for each loop and we are not using arrow function then we need to provide thisArg parameter (this)

uses of thisArg in foreach loop

map():

the map calls a provided callback function once for each element in an array, in order, and constructs a new array from the results. the callback is invoked only for indexes of the array which have assigned values, including undefined

var new_array = arr.map(function callback(currentValue[, index[, array]]) { // Return element for new_array }[, thisArg])

syntax of map()

The callback is invoked with three arguments:

  1. the value of the element
  2. the index of the element
  3. the Array object being traversed

In the term of syntax and the way of using boths are same.

fundamental are same for both

What is the difference ?:

  1. forEach return is undefined. whereas map returns a new array
  2. forEach changes the original array whereas map does not change original array instead create a copy of the original array

When we should go for forEach and map?

Performing non-transformation like processing on each element. For example, saving all elements in the database

forEach

Obtaining an array containing the output of some processing is done on each element of the array. For example, obtaining an array of lengths of each string in the array

map

When not to use map():

Since map builds a new array, using it when you aren’t using the returned array is an anti-pattern; use forEach or for-of instead.

You shouldn’t be using map if:

  1. you’re not using the array it returns; and/or
  2. you’re not returning a value from the callback.

Benefits of Map over forEach

#1. the map doesn’t alter the original array if you don’t want to change the original array but wants to perform the operation on it.
#2. It is easy to use with other array functions like filter, reduce, find, etc.

map-with-filter-map-vs-foreach
Example of map() with filter

If you see the above example, where we took an array then perform multiplication on that array using map(). Now map return modified array on which we perform filter() to find out even number in the array.

Can we use “break” in forEach()

forEach is unbreakable. You can not break out of a forEach loop when going through an Array.

References:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
https://stackoverflow.com/questions/34426458/javascript-difference-between-foreach-and-map/34426481
https://programmingwithmosh.com/javascript/whats-the-difference-between-foreach-and-map-in-javascript/

Read more: power console in javascript