DEV Community

Cover image for forEach vs map method javascript
sagar
sagar

Posted on

1

forEach vs map method javascript

forEach and map method both use to iterate over arrays , but they serve different purposes and have distinct behaviors.

1.forEach method

The forEach method is used for iterating through each element of an array. It doesn’t create a new array; instead, it directly modifies the elements of the existing array.

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

numbers.forEach(function(number) {
  console.log(number * 2);
});

// Output:
// 2
// 4
// 6
// 8
// 10
Enter fullscreen mode Exit fullscreen mode

forEach used when your purpose is to iterate over each element of array without needing to create new array.

2. map method

map method on other hand also used for iterating through each element of an array but it can return new modified array without changing the original array

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

const doubledNumbers = numbers.map(function(number) {
  return number * 2;
});

console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]
Enter fullscreen mode Exit fullscreen mode

map method used when your purpose is to return new modified array

In summary:

  • Use forEach when you want to iterate through an array and perform side effects or actions on each element without creating a new array.

  • Use map when you want to iterate through an array, transform its elements using a function, and create a new array with the transformed values.

Note:- Remember that both methods iterate over each element in the array, so the provided function will be executed for each element. The main difference lies in the purpose and outcome of using each method.

Heroku

Simplify your DevOps and maximize your time.

Since 2007, Heroku has been the go-to platform for developers as it monitors uptime, performance, and infrastructure concerns, allowing you to focus on writing code.

Learn More

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay