Difference between forEach and map methods in JavaScript

Difference between forEach and map methods in JavaScript

In this tutorial, we are going to learn about the difference between forEach method and map method in JavaScript with the help of examples.

consider we have an array of users we need to loop through each user and log the each user name in the console.

const users = [
  { name: "king", received: false },
  { name: "sai", received: true }
];

forEach method

The forEach() method takes the callback function as an argument and run once on each element in the array.

Note: forEach method can’t return anything.

We can use forEach method to log each user.name in the console.

users.forEach(user=>{
    console.log(user.name);
})

map Method

The map method takes the callback function as an argument and returns the new array with results of calling a callback function on each element.

We can also use map method to log each user.name.

users.map(user=>{
    console.log(user.name);
})

But it is the wrong way to use map method, instead of logging the user.name we can use map method to transform the all user names present inside the users array to uppercase.

const upperCase = user => {
  return {
    ...user,
    name: user.name.toUpperCase()
  };
};

const updatedUsers = users.map(upperCase);

console.log(updatedUsers);


/*output of updatedUsers array
   [
     { name: "KING", received: false },
     { name: "SAI", received: true }
   ];
*/

Note: map method doesn’t modify the original array, instead of it creates a new array with modified results.

If you use forEach method to transform the user names to uppercase it won’t work because forEach doesn’t return anything.

const upperCase = user => {
  return {
    ...user,
    name: user.name.toUpperCase()
  };
};

const updatedUsers = users.forEach(upperCase);

console.log(updatedUsers); // undefined

Now let’s use both methods to the display the user.name in the screen instead of logging in the console.

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Hello</title>
    <meta charset="UTF-8" />
</head>

<body>
    <div id="app"></div>
    <script src="index.js"></script></body>

</html>
index.js
const app = document.getElementById("app");

const users = [
  { name: "king", received: false },
  { name: "sai", received: true }
];

const upperCase = user => {
  return {
    ...user,
    name: user.name.toUpperCase()
  };
};

users.map(upperCase).forEach(user => {  const h1 = document.createElement("h1");  h1.textContent = user.name;  h1.addEventListener("click", () => {    alert(`Don't hit ${user.name}`);  });  app.appendChild(h1);});

In the above code first, we transformed the all user names to uppercase then we chain it with forEach method and created an h1 element for each user then appended it as a child to app.

Conclusion

  • Use forEach method only when you need to do something with each item in the array, like in the above example we created an h1 element for each item in the array.
  • Use map method only when you need to something with an array of items, like in the above example we used map method to transform the user names to uppercase, without modifying the original array so that we can use the original array for other purposes.