Javascript map vs forEach

In this article, we learn about JavaScript map vs forEach and as well as when it is appropriate to use one over the other.

 

Javascript map vs forEach

 

 

JavaScript map vs forEach

Both map and forEach are array methods used to manipulate arrays. However, they are used for different purposes and have some key differences:

 

Javascript map() method

 

The map() is used to create a new array by applying a function to each element in the original array and returning the result as a new array. For example:


let numbers = [1, 2, 3, 4, 5];

let multiple = numbers.map(function(num) {

return num * 2;

});

console.log(multiple); // [2, 4, 6, 8, 10]

 

Javascript forEach

On the other hand, foreach is used to execute a provided function for each element in an array. It does not return a new array but instead, it operates directly on the original array.


let numbers = [1, 2, 3, 4, 5];

numbers.forEach(function(num) {

console.log(num * 2);

});

// 2

// 4

// 6

// 8

// 10

 

When is it appropriate to use the map and when is it suitable to use forEach in Javascript?

 

map and forEach are both used to iterate over arrays in Javascript, but they are used for different purposes. Here are some key points for when to use each method:

 

Use a map when you want to:

 

  • Transform the elements of an array into a new array of different values
  • Create a new array based on the results of a function applied to each element in the original array
  • Return a new array without modifying the original array

 

 

Use forEach when you want to:

 

  • Perform a side effect for each element in an array, such as updating a counter, printing values to the console, or modifying the original array directly.
  • Loop over an array without creating a new array.

 

 

 

The map is a pure function, meaning it doesn’t modify the original array and always returns a new array based on the transformations performed on each element of the original array. forEach is not a pure function, as it operates directly on the original array and can modify its values.

 

In general, if you need to transform an array into a new array of values, the map is the method to use. If you need to perform some operations on the elements of an array for side effects, use forEach.

 

 

Conclusion

 

Both map and forEach are two important array methods in JavaScript that manipulate array elements. I hope now you understand the use of each method is crucial for writing efficient and robust code.