Home > Web Front-end > JS Tutorial > body text

forEach vs map method javascript

WBOY
Release: 2024-08-12 18:41:03
Original
1090 people have browsed it

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
Copy after login

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]
Copy after login

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.

The above is the detailed content of forEach vs map method javascript. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template