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.

Billboard image

Deploy and scale your apps on AWS and GCP with a world class developer experience

Coherence makes it easy to set up and maintain cloud infrastructure. Harness the extensibility, compliance and cost efficiency of the cloud.

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

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay