Author -  Sai gowtham

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 and 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.

Css Tutorials & Demos

How rotate an image continuously in CSS

In this demo, we are going to learn about how to rotate an image continuously using the css animations.

How to create a Instagram login Page

In this demo, i will show you how to create a instagram login page using html and css.

How to create a pulse animation in CSS

In this demo, i will show you how to create a pulse animation using css.

Creating a snowfall animation using css and JavaScript

In this demo, i will show you how to create a snow fall animation using css and JavaScript.

Top Udemy Courses

JavaScript - The Complete Guide 2023 (Beginner + Advanced)
JavaScript - The Complete Guide 2023 (Beginner + Advanced)
116,648 students enrolled
52 hours of video content
$14.99 FROM UDEMY
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
631,582 students enrolled
49 hours of video content
$24.99 FROM UDEMY
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
Vue - The Complete Guide (w/ Router, Vuex, Composition API)
203,937 students enrolled
31.5 hours of video content
$14.99 FROM UDEMY