DEV Community

Cover image for forEach() or map() ? When to use?
Sakib Ahmed
Sakib Ahmed

Posted on

forEach() or map() ? When to use?

In this article we'll discuss about forEach and map method in javascript. Which one best and when to use each one.

In JavaScript, forEach and map are two of the most popular methods to work with arrays. Primarily both use to iterate array. So this make a little bit confusion which one we should use.

forEach Method:

forEach is used to run a function on each element without changing the array. Note, forEach method doesn’t return anything, if you try to get the return value of the forEach method, you will get undefined. Since it allows you to modify the source array itself, it’s a mutator method.

Code Example:

// given array
let arr = [1, 2, 3, 4, 5];

//output the square of each number
let returnVal= arr.forEach(num => 
  console.log(`${num} x ${num} = ${num * num}`)
);

//the array hasn't changed
console.log(arr); 
console.log(returnVal);
Enter fullscreen mode Exit fullscreen mode
// Output
// 1 x 1 = 1
// 2 x 2 = 4
// 3 x 3 = 9
// 4 x 4 = 16
// 5 x 5 = 25
// [1,2,3,4,5]
// undefined
Enter fullscreen mode Exit fullscreen mode

forEach not returning any new array. The return value of this method is ignored, and the original array doesn't change. The return value of forEach is always undefined.

map Method

Similar to forEach method but return NEW ARRAY. It's create new array with return value, but forEach give us undefined. But map doesn't change the given array, so we can say that it’s an immutable method.

Code example:

// given array
let arr = [1, 2, 3, 4, 5];

//output the square of each number
let returnVal= arr.map((num) => num * num)

//the array hasn't changed
console.log(arr); 
console.log(returnVal);
Enter fullscreen mode Exit fullscreen mode
// Output
 [1,2,3,4,5]
 [1,4,9,16,25]
Enter fullscreen mode Exit fullscreen mode

So, as you see, map method return a new array with the returning value but doesn't change the given array. Given array remains unchanged

So what is the differences between forEach and map?

As I said, map returns a new array but forEach return nothing. So, the main difference between map and forEach is that the map method returns a new array by applying the callback function on each element of an array, while the forEach method doesn’t return anything.
forEach method can be use to mutate the source array. Instead, it's great for when you need to do some action with each element of the array.

Which one to use?

If you’re planning to alter the array elements by applying a function, you should use the map method, since it doesn’t modify the original array and returns a new array. In this way, the original array is kept intact. On the other hand, if you want to loop through all the elements of an array and don’t need a returned array, use the forEach method.

Top comments (0)