
In this article we'll discuss aboutforEach
andmap
method in javascript. Which one best and when to use each one.
In JavaScript,forEach
andmap
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 theforEach
method, you will get undefined. Since it allows you to modify the source array itself, it’s a mutator method.
Code Example:
// given arrayletarr=[1,2,3,4,5];//output the square of each numberletreturnVal=arr.forEach(num=>console.log(`${num} x${num} =${num*num}`));//the array hasn't changedconsole.log(arr);console.log(returnVal);
// 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
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 arrayletarr=[1,2,3,4,5];//output the square of each numberletreturnVal=arr.map((num)=>num*num)//the array hasn't changedconsole.log(arr);console.log(returnVal);
// Output[1,2,3,4,5][1,4,9,16,25]
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'sgreat for when you need to do some action witheach 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)
For further actions, you may consider blocking this person and/orreporting abuse