map allows transforming the elements of an array, this implies several advantages
For example given the following list of employees
const employees = [
{
id: 1,
firstName: "john",
lastName: "doe",
salary: 10000,
},
{
id: 2,
firstName: "andy",
lastName: "johnson",
salary: 15000,
},
];
And suppose you require only their salaries, you can do the following
const salaries = employees.map((employee) => employee.salary);
// output [ 10000, 15000 ]
Now suppose you need to get their salaries next to their full names, you can try the following
const employeeList = employees.map(({ id, firstName, lastName, salary }) => ({
id,
fullName: `${firstName} ${lastName}`,
salary,
}));
// output [{ fullName: 'john doe', salary: 10000 }, { fullName: 'andy johnson', salary: 15000 }]
You accomplish this without loops, which is a plus
Another advantage is that it allows you to avoid unexpected results, for example imagine that you need a copy of the list of employees
const newEmployees = employees;
And then you modify the salary of one of the employees from the original list
employees[0].salary = 25000;
This operation will affect both lists, as you can see here
console.log(JSON.stringify(employees, null, 2));
console.log(JSON.stringify(newEmployees, null, 2));
output
[
{
"id": 1,
"firstName": "john",
"lastName": "doe",
"salary": 25000
},
{
"id": 2,
"firstName": "andy",
"lastName": "johnson",
"salary": 15000
}
]
[
{
"id": 1,
"firstName": "john",
"lastName": "doe",
"salary": 25000
},
{
"id": 2,
"firstName": "andy",
"lastName": "johnson",
"salary": 15000
}
]
John has salary of 25000 in the original list and the new list. The reason is that copies by reference
To avoid this, map allows you to copy to get a new list and in consequence free of unexpected results
const anotherNewEmployess = employees.map(
({ id, firstName, lastName, salary }) => ({ id, firstName, lastName, salary })
);
output
[
{
"id": 1,
"firstName": "john",
"lastName": "doe",
"salary": 25000
},
{
"id": 2,
"firstName": "andy",
"lastName": "johnson",
"salary": 15000
}
]
[
{
"id": 1,
"firstName": "john",
"lastName": "doe",
"salary": 10000
},
{
"id": 2,
"firstName": "andy",
"lastName": "johnson",
"salary": 15000
}
]
In this example there are better ways to do it, or more compact ones like Array.from() or destructuringor some other hidden jutsu that SO boys know
The latter is very relevant in the context of functional programming, where the data is immutable. And many libraries and frameworks adopt it and recommend it
I have presented an example other than yours because I believe it is more easily demonstrates the usefulness of map
I hope this explanation is useful to you
mapis the best choice in such scenario.