The forEach() method is used to execute a function for each of the items in an array. The callback function will normally contain some instructions that will be performed on each of the array items.
Syntax
array.forEach(callbackFunction);
The callback function accepts three arguments, the arguments are
- CurrentItem: the methods iterate through the items in the array one after the other. This argument represents each individual item in the array.
- Index: this argument represents the index number of the item in the array. It is useful for numbering the items. This argument is optional.
- Array: the third argument is the array itself. It is used to access the entire content of the array. This argument is also optional.
In most cases though, only the first argument is used. You can use either function keyword or arrow function for the callback.
Syntax
array.forEach( (item, index, array) => {
// perform a task(s)
});
array.forEach( function(item, index, array){
// perform a task(s)
});
Example
const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
const loopCities = cities.forEach((city) => {console.log(`I love ${city}`)})
Example with the three arguments
const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
const loopCities = cities.forEach((city, index, array) =>
{console.log(`${index + 1}. ${city} is the best of these four cities (${array}) ` )
})
The forEach method does not iterate empty values.
The commas in the array not preceded immediately by any value represented empty values. The forEach() completely ignores those cells.
Iterating through array of objects with forEach
forEach() can be used to iterate through array of objects. The current object will be the current item, and you can then access the properties of the object.
const students = [
{name:'Ada', score:90},
{ name:'Ola', score: 89},
{name:'Tobi', score:45},
{name:'Eze', score: 55}
]
const result = students.forEach(student => {
console.log(`${student.name} scored ${student.score} marks`)
})
Looping conditional statement with forEach()
const students = [
{name:'Ada', score:90},
{ name:'Ola', score: 89},
{name:'Tobi', score:45},
{name:'Eze', score: 55}
]
const result = students.forEach(student => {
if (student.score >= 86) {
console.log(`${student.name} scored ${student.score} marks: :) excellent`)
} else {
console.log(`${student.name} scored ${student.score} marks: :( you can do better`)
}
})
Iterating NodeList with forEach
Although forEach is specifically designed for arrays, and does not work for other data types. However, NodeList and other array like objects are exempted. NodeList is a collection of node objects, which represent elements, attributes, texts and other parts of an HTML document.
Illustration
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<script>
const items = document.querySelectorAll('li');
items.forEach((item, index) => {
item.textContent = `this is the number ${index + 1} item`;
})
</script>
</body>
forEach does not return a value.
The forEach method is a void method (it does not return a value). It is basically used to perform operations and cannot be used to create another array, or to mutilate or transform an existing array.
Illustration
const cities = ['Abuja', 'Cairo', 'London', 'Paris'];
const loopCities = cities.forEach((city) => {console.log(`I love ${city}`)})
As can be seen from the above illustration, the cities array remained unchanged. And the loopCities variable that the forEach method was assigned to returned undefined.
Pros of using forEach for iteration
• The forEach loop has a simpler and easier to read syntax.
• Its predefined arguments make it easier to avoid mistake.
Cons of using forEach for iteration
• Unlike for loop where you can terminate the iteration midway with the break or continue statement, with ForEach such option is not available.
• The forEach method does not return a value and cannot be used to modify or transform arrays.
• You can’t use forEach with async functions because forEach cannot handle dependencies between async operations.
• It is not as efficient in terms of performance when compared to other traditional looping alternatives.
Best practices
• Avoid using forEach when working with asynchronous operations.
• Do not use forEach if you wish to transform an array or to create a new array.
• Keep the callback function simple, avoid multiple logic.
Summary
• The forEach() method is used to execute a callback function for each of the items in an array.
• The callback function accepts three arguments; currentItem, indexNumber and the Array itself.
• In most cases, only the first argument is utilized
• Syntax for forEach is
array.forEach( (item, index, array) => {
// perform a task(s)
});
array.forEach( function(item, index, array){
// perform a task(s)
});
• forEach() can be used to iterate array of objects and nodeLists
• forEach() does not return a value hence cannot be used to create new arrays or transform existing arrays.
Top comments (0)