Does the forEach () method mutate an Array?
How to use the forEach method() in a Practical Application
The forEach() method is one of the most common array methods in JavaScript. In this short tutorial, we will examine how the array can be used in practical applications.
As the name suggests, the forEach() method applies a callback function to each element in the provided array. Its syntax looks like this:
array.forEach(callbackFunction, thisArg);
The callback functions takes in several parameters:
Array.forEach(function(element, index, array),thisArg)
where:
element: is the value of the current element being iterated
index: is the index of the current element being iterated
array: this is the original array for which the map function has been applied to
thisArg(optional): this is the value to use as
this
when executing the callback function.
The forEach() method doesn’t return a value, so if you assign it to a value, the resulting value will be undefined.
const result = Array.forEach(function(element, index, array),thisArg)
// the value of result will be undefined
Let’s look at some examples,
Suppose you have this array of names:
const peeps = ["erick","erickson","johnson"]
If we needed to capitalize the first letter of each word, we could use forEach() method to do that:
peeps.forEach((peep, index) => {
//conditon goes here
});
Inside the function, we will first get the first letter of each name using charAt(0), then we will apply toUpperCase()
to the first letter, essentially converting it to uppercase. After that, we will concatenate it with the result of slicing() the first letter of the name.
The result will then be assigned to the same index in the original array.
peeps.forEach((peep, index) => {
peeps[index] = peep.charAt(0).toUpperCase() + peep.slice(1);
});
console.log(peeps);
The result will look like this:
If you attempt to assign the result of the forEach()
method, you will get undefined since forEach()
method doesn’t return a value.
Let’s look at another example; suppose we have a database of employees which look like this:
const employees = [
{
id: 1,
fullName: "Erick Erickson",
country: "USA",
city: "New York",
home: "123 Main St"
},
{
id: 2,
fullName: "Alice Johnson",
country: "UK",
city: "London",
home: "456 Elm St"
},
{
id: 3,
fullName: "Bob Smith",
country: "Canada",
city: "Toronto",
home: "789 Oak St"
},
{
id: 4,
fullName: "Charlie Brown",
country: "Australia",
city: "Sydney",
home: "101 Maple St"
}
];
Given this data, can we use the forEach() method to add a new key called address, which combines the values of the country, city, and home, resulting in something like this for each employee:
{
id: 4,
fullName: "Charlie Brown",
country: "Australia",
city: "Sydney",
home: "101 Maple St",
address: "Sydney,Australia - 101 Maple St"
}
To add the address key to each employee, we will iterate over the employee's array and, for each employee, pass a function that will take an employee as a parameter. Inside the function, we will use the dot notation to create a new key called address and assign the result to a combination of the country, city, and home values.
employees.forEach(employee=>{
employee.address = `${employee.country},
${employee.city}-${employee.home}`
})
console.log(employees)
Here is the output:
[
{
id: 1,
fullName: 'Erick Erickson',
country: 'USA',
city: 'New York',
home: '123 Main St',
address: 'USA, New York-123 Main St'
},
{
id: 2,
fullName: 'Alice Johnson',
country: 'UK',
city: 'London',
home: '456 Elm St',
address: 'UK, London-456 Elm St'
},
{
id: 3,
fullName: 'Bob Smith',
country: 'Canada',
city: 'Toronto',
home: '789 Oak St',
address: 'Canada, Toronto-789 Oak St'
},
{
id: 4,
fullName: 'Charlie Brown',
country: 'Australia',
city: 'Sydney',
home: '101 Maple St',
address: 'Australia, Sydney-101 Maple St'
}
]
For better presentation, let’s display the data in a table; your HTML will look like this:
<h1>Employee Addresses</h1>
<table>
<thead>
<tr>
<th>Staff ID</th>
<th>Full Name</th>
<th>Country</th>
<th>City</th>
<th>Home</th>
<th>Address</th>
</tr>
</thead>
<tbody id="employee-table">
<!-- Employee data will be displayed here -->
</tbody>
</table>
Get the DOM table element;
const tableBody = document.getElementById('employee-table');
Append the data to the rows:
employees.forEach(employee => {
const address = `${employee.country}, ${employee.city} -
${employee.home}`;
const row = document.createElement('tr');
row.innerHTML = `
<td>${employee.id}</td>
<td>${employee.fullName}</td>
<td>${employee.country}</td>
<td>${employee.city}</td>
<td>${employee.home}</td>
<td>${address}</td>
`;
tableBody.appendChild(row);
});
Summary
Although the forEach() method doesn't directly mutate an array, you can utilize the callback function passed to forEach() to perform operations that result in array mutation, as demonstrated in the examples.
Know someone who'd love this tutorial? Share the knowledge, and let's master JavaScript together! 🎓