Understanding the Differences: forEach vs map in JavaScript

map and forEach are both methods that can be used to iterate over arrays. However, they have some differences in their functionality.

forEach is a method that executes a provided function once for each element in an array. It does not return a new array, but instead modifies the original array.

Syntax:

array.forEach(function(currentValue, index, array) {
  // code to be executed for each element
});        

Let's understand the line It does not return a new array, but instead modifies the original array

const names = ["Rohit","Aakash","Vinay","Ashish","Vasu"];

const newNames=name.forEach(function(name, index, array) {
  array[index] = name + "DEV";
});
console.log(newName) // Undefined

console.log(names); // Output: ['RohitDEV', 'AakashDEV', 'VinayDEV', 'AshishDEV', 'VasuDEV']        

Here we can see the original array names are changed and newNames is coming undefined means it is not returning anything.

map is a method that creates a new array with the results of calling a provided function on every element in the original array. It does not modify the original array.

Syntax:

var newArray = array.map(function(currentValue, index, array) {
  // code to be executed for each element
  return result;
});        
const names = ["Rohit","Aakash","Vinay","Ashish","Vasu"];

const newName =names.map(function(name, index, array) {
  return name + "DEV";
});
console.log(newName); // Output: ['RohitDEV', 'AakashDEV', 'VinayDEV', 'AshishDEV', 'VasuDEV']

console.log(names); // Output: ['Rohit', 'Aakash', 'Vinay', 'Ashish', 'Vasu']        

Here we can see map is returning the new Array with updated value and the original value of Array is not changing.

So, The main difference between map and forEach is that map returns a new array with the results of the function applied to each element, while forEach does not return anything. Both map and forEach can modify the original array if the callback function modifies its elements.

Note: If you are using map((item, index, arr)) and modify the arr parameter within the callback, it can change the original array. However, if you do not use or modify the third parameter (arr), the original array will remain unaffected.

let numbers = [1, 2, 3, 4];

// Typical use of map (does not modify the original array)
let doubledNumbers = numbers.map(num => num * 2);
console.log(doubledNumbers); // Output: [2, 4, 6, 8]
console.log(numbers); // Output: [1, 2, 3, 4]

// Modifying the original array using the third parameter
let modifiedNumbers = numbers.map((num, index, arr) => {
    arr[index] = num * 3; // Modifying the original array
    return num * 2; // Creating a new array with each element doubled
});        







Aabhas Saxena

IITian | Co - Founder Khabri Bai | Education was my escape from poverty, and it can be yours too ?? | Let's stay in touch, and navigate our paths side by side ??

2 周

forEach does not change the original array , here it got changed in your example because you changed it, same can be done in map also.Also please select variable names carefully you have misspelled them. Without the return keyword map will not be able to return the new value instead it will return an array with all values undefined.

  • 该图片无替代文字
回复
Azlan Rasool

Computer Scientist $ sudo rm -rf conformity

6 个月

Rohit, your article was the first thing that popped up when I searched for forEach vs map, array methods. The last paragraph seems to imply that only forEach can modify the original array. Whereas, both map and forEach can do so. Hence, it is a similarity, rather than a difference. So, the only true difference listed in this article is that, map returns a new (modified) array and forEach does not return anything. Correct it.

  • 该图片无替代文字
Muhammad Muhammad

JavaScript Engineer - MERN | [ReactJS, NextJS, Edgio, NodeJs-NestJs, SQL/NoSql- PostgreSQL, Prisma, Redux | zustand, typescript, Shopify Customization]

6 个月

Why should we use for each if the map can do everything for us, like returning a new array or modifying an existing one

回复

Good explanation but the foreach function doesn't modify the original array. It just executes a function for each item of an array. The first and last paragraph may confuse the reader.

Ashish Chowdhury

Manager Quality Engineering

1 年

Very useful information ??

要查看或添加评论,请登录

社区洞察

其他会员也浏览了