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]
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
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)
Great article π
Thanks Vlad. I appreciate