javaScript forEach Array Method

Kemi OwoyeleKemi Owoyele
4 min read

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:

  1. CurrentItem: the methods iterate through the items in the array one after the other. This argument represents each item in the array.

2. This argument represents the index number of the item in the array. It is useful for numbering the items. This argument is optional.

3. 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, only the first argument is used. You can use either the function keyword or the 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 over empty values.

The commas in the array, not preceded immediately by any value, represented empty values. The forEach() function completely ignores those cells.

Iterating through an array of objects with forEach

forEach() can be used to iterate through an array of objects. The current object will be the current item, and with that, 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 void (it does not return a value). It is 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 the for loop, where you can terminate the iteration midway with the break or continue statement, with ForEach, such an 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 create a new array.

  • Keep the callback function simple, and avoid multiple logics.

0
Subscribe to my newsletter

Read articles from Kemi Owoyele directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Kemi Owoyele
Kemi Owoyele

frontend developer and technical writer