What is the difference between forEach and map method

The JavaScript language, and within the scope of the topic of loops, iteration, and arrays? Also, you stumbled upon these two methods, Array.forEach() and Array.map(). Finally, confused? Not to worry because in this post, we will show you the difference between these two methods.

The syntax of forEach and map
What is Array.forEach?
The forEach method allows you to run a function/method for each element in the array.

//the syntax   
[].forEach(function(item, index, array){
    
      
    //do your stuff here...  
});

argument description requires
item the item currently being processed is
index the index of the current item in the array no
array the array forEach is called no
quick example

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

insert image description here

The argument description requires
item The item currently being processed is
index The index of the current item in the array No
array The array forEach is called No

As you can see, our forEach shows the three parameters of the method by passing the console.log method. It's simple, isn't it? We'll dig into that in a later section.

What is Array. map?
The map method returns a new set of arrays without changing the original arrays.

grammar

//the syntax: 
[].map(function(currentValue, index,currentArray){
    
    
//do your stuff here ...
}, thisValue)

Argument Description Required
currentValue The item currently being processed is
the index of the current item in the index array No
currentArray The array map is called No
thisValue Used as this value when executing callbacks No
Quick Example

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

insert image description here

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

Difference between forEach and map
Now that we have seen the syntax of these two array methods, we can answer their differences. Will try to explain the difference using code examples. But, before going into every detail, we need some form of data.

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
        }];

Every time
no result value or no value is returned
iterates over a list and performs some side-effecting operation on each list. If you need to do something meaningful, you can do some side effects while iterating.

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

insert image description here

Thoughts on the forEach method
Every time I use the forEach method, I observe that it describes the flow of control. No mystery, is there? Therefore, it can be said that this is a priority.

map
returns a new list without changing anything else
has no side effects, it doesn't change the original array list

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);

insert image description here

Again, back to my observations, but with the map method, I've observed that it's kind of like dataflow. Meaning, when you have an input array, it will output a new array by using this method. Therefore, it can be said to be functional.

Guess you like

Origin blog.csdn.net/u014249305/article/details/110731355
Recommended