Click here to Skip to main content
15,922,309 members
Articles / Programming Languages / Javascript

What’s the Difference between forEach and map Methods?

Rate me:
Please Sign up or sign in to vote.
3.67/5 (2 votes)
1 Sep 2020CPOL3 min read 4.1K   2  
Resolving confusion about the forEach and map methods
In this post, we look at what is the Array.forEach and what is the Array.map? We will also take a look at the difference between forEach and map, as well as thoughts on the map method.

Introduction

Are you currently learning the JavaScript language and within the subject area of loops, iteration, and arrays? Plus you stumbled upon these two methods, Array.forEach() and Array.map(). Finally, confused? No worries, because in this post, we are going to show you the difference between these two methods.

Syntax of forEach & map

What is the Array.forEach?

The forEach method allows you to run a function/method for every element inside the array.

The Syntax

JavaScript
//the syntax   
[].forEach(function(item, index, array){  
    //do your stuff here...  
});
Argument Description Required
item The current item being processed Yes
index The index of the current item in the array No
array The array forEach was called upon No

Quick Example

JavaScript
["apple", "mango", "avocado", "dragon fruit"].forEach(console.log);

Output

Image 1

As you can see, we have shown the three arguments of the forEach method by passing the console.log method. Easy, isn’t it? We will get in-depth in the later section.

What is the Array.map?

The map method returns a new set of arrays, but doesn’t change the original array.

The Syntax

JavaScript
//the syntax: 
[].map(function(currentValue, index,currentArray){
//do your stuff here ...
}, thisValue)
Argument Description Required
currentValue The current item being processed Yes
index The index of the current item in the array No
currentArray The array map was called upon No
thisValue Value to use as this when executing callback No

Quick Example

JavaScript
["apple", "mango", "avocado", "dragon fruit"].map((currentValue) => currentValue.toUpperCase());

Output

Image 2

As you can see, we have shown how the map method returns a new set of arrays in uppercase.

The Difference between forEach and map

Now that we have seen the syntax of these two array methods, we can go and answer their differences. Will do our best to explain the difference with the use of code samples. However, before going to each detail, we need some form of data.

JavaScript
const employees =
    [{
        employee: 'Eleanor R. Crane',
        company: 'Tellus Faucibus Leo Incorporated',
        dailyRate: 0,
        salary: 15200
    },
    {
        employee: 'Haviva E. Lane',
        company: 'Eu Neque Pellentesque Incorporated',
        dailyRate: 0,
        salary: 13333
    },
    {
        employee: 'Merrill F. Morrison',
        company: 'Lobortis Quam Ltd',
        dailyRate: 0,
        salary: 1450
    },
    {
        employee: 'Halee L. Hensley',
        company: 'Elit Corp.',
        dailyRate: 0,
        salary: 15872
    },
    {
        employee: 'Hamish T. Trevino',
        company: 'Rhoncus LLC',
        dailyRate: 0,
        salary: 14214
        }];

forEach

  • has no result value or doesn’t return anything
  • iterates over a list and applies some operation with side effects to each list. If you need to do something meaningful, you can do some side effects while iterating.
JavaScript
const TOTAL_WORKING_DAYS = 261;

//Horrible in my opinion, worst someone will say it is ugly. 
const dailyRate = (item, index, array) => array[index].dailyRate = 
                   Math.floor(((item.salary * 12) / (TOTAL_WORKING_DAYS)));

//undefined as forEach doesn't return any results.
let dailyRateEmployeeResults = employees.forEach(dailyRate);

console.log(dailyRateEmployeeResults);    //undefined

console.log(employees);                   //With side effects

Output

Image 3

Thoughts on the forEach Method

Every time working with the forEach method, I have observed that it describes the control flow. No mystery, isn’t it? Hence, we can say that it is imperative.

map

  • returns a new list without changing anything else
  • has no side effects, it doesn’t change the original array-list
JavaScript
const TOTAL_WORKING_DAYS = 261;

const getDailyRate = salary => Math.floor(((salary * 12) / (TOTAL_WORKING_DAYS)));

const dailyRate = employee => Object.assign({}, 
                  { employee: employee.employee, dailyRate: getDailyRate(employee.salary) });

//Returns a new set of employees with dailyRate and name
const newEmployees = employees.map(dailyRate);

//new data
console.log(newEmployees);

//old data
console.log(employees);

Output

Image 4

Thoughts on the Map Method

Again, going back to my observations but with the map method, I have observed that it is somewhat a flow of data. Meaning, when you have an input array, then it outputs a new array through the use of this method. Hence, we can say that it is functional.

Conclusion

It is obvious that these two methods have opposing views when it comes to usage which has its own pros and cons. Therefore, we can conclude that the forEach method is using the imperative paradigm while the map method uses the functional programming paradigm.

Summary

We have seen the difference between forEach and map. We started from its syntax all the way up to the differences with code samples. I hope you have enjoyed this article, as I have enjoyed writing it. Stay tuned for more. Many thanks, until next time, happy programming!

History

  • 1st September, 2020: Initial version

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Philippines Philippines
Jin humbles himself as a C# programmer and a web developer, who loves backend and middleware development and still improving his skills at the front-end arena. He loves what he does, but far from perfect, here is a list of what he loves to do: read, write and code.
This is a Social Group

2 members

Comments and Discussions

 
-- There are no messages in this forum --