Understanding the difference between Map and ForEach method.

Understanding the difference between Map and ForEach method.

ยท

2 min read

Introduction

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 questions if you are not clear about any of these methods. Have an amazing weekend and see you next week. ๐Ÿ˜€

ย