DEV Community

Cover image for Understanding the difference between Map and ForEach method.
Amrasakpare Lawrence
Amrasakpare Lawrence

Posted on • Edited on

Understanding the difference between Map and ForEach method.

Have you ever wondered about the difference between map and forEach when dealing with arrays in JavaScript? If your answer is Yes then Let's take a stroll through these methods! πŸšΆβ€β™‚οΈ

map Method: Transform and Collect

Think of the map method as a transformation machine for arrays. It takes an array, processes each item, and creates a brand-new array with the processed items. It's like sending each item through a transformation process and collecting the transformed items in a new basket. Let’s see an example πŸ‘‡πŸ½
For example, imagine you have an array of numbers and you want to double each number(. Here is how you would do it πŸ‘‡πŸ½

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

const doubledNumbers = numbers.map(number => number * 2);
// Result: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

Here, map applies the number * 2 operation to each number in the array and collects the doubled numbers in a new array called doubledNumbers.

forEach Method: A Guided Tour

The forEach method is like a tour guide that takes you through each item in an array and shows you around. It doesn't change the items or create a new array. It's like taking a walk through a garden and admiring the flowers without picking them.

For example, let's say you have an array of names and you just want to log each name. Here is how you would do it. πŸ‘‡πŸ½

const names = ['Lawrence', 'Dan', 'Trecia'];

names.forEach(name => console.log(name));
// Output: Lawrence, Dan, Trecia
Enter fullscreen mode Exit fullscreen mode

With forEach, you're walking through the array and logging each name, but you're not changing the array itself.

Summary

  • map transforms items and creates a new array with transformed items.
  • forEach guides you through items, letting you perform actions, but doesn't create a new array or modify the existing one.

Conclusion

That’s all guys. Hope you now understand what or how the map and forEach method works. You can also ask question if you are not clear about any of these methods. Have an amazing weekend and see you next week. πŸ˜€

Top comments (2)

Collapse
 
volodyslav profile image
Volodyslav

Great article πŸ‘

Collapse
 
devlawrence profile image
Amrasakpare Lawrence

Thanks Vlad. I appreciate