Close
All

Understanding the difference between Map and ForEach method

Understanding the difference between Map and ForEach method

Let’s switch gears to a scenario where you need to update each element of an array. Consider an array of user objects, and you want to mark all users above a certain age as “verified.” Here’s where the forEach method plays its role:

const users = [
{ name: 'Alice', age: 28, verified: false },
{ name: 'Bob', age: 35, verified: false },
{ name: 'Eve', age: 22, verified: false }
];

users.forEach(user => {
if (user.age > 30) {
user.verified = true;
}
});

In this case, the forEach method iterates through each user object and updates the verified property for users above the age of 30.

Leveraging the Power: Where to Choose What?

When to Choose Map

Leave a Reply

Your email address will not be published. Required fields are marked *