JavaScript Array forEach() - Execute Function on Elements

Updated on November 28, 2024
forEach() header image

Introduction

The JavaScript forEach() method is an integral part of the Array prototype that allows for executing a function on each element in an array. This method simplifies the process of iterating over array elements, eliminating the need for traditional loop constructs like for or while, thereby making the code more readable and concise.

In this article, you will learn how to effectively utilize the forEach() method in an array context. Discover the basics of using this method with examples including array manipulation, integration with other functions, and handling asynchronous operations.

Basic Usage of forEach()

Execute a Simple Function on Each Item

  1. Define an array of items.

  2. Use the forEach() method to apply a function to each element.

    javascript
    const fruits = ['apple', 'banana', 'cherry'];
    fruits.forEach(function(item, index) {
        console.log(index, item);
    });
    

    This code prints each fruit in the array along with its index to the console. The forEach() method takes a callback function as an argument, which is applied to every element of the array.

Modify Array Elements

  1. Start with a numeric array.

  2. Use the forEach() method to modify each element.

    javascript
    const numbers = [1, 2, 3];
    numbers.forEach((value, index, arr) => {
        arr[index] = value * 10;
    });
    console.log(numbers);
    

    Here, each number in the array numbers is multiplied by 10. The forEach() method provides access not just to the array element and its index, but also to the array itself, allowing direct modification.

Advanced Usage of forEach()

Using forEach() with Object Arrays

  1. Create an array of objects.

  2. Use forEach() to iterate over the objects and perform operations.

    javascript
    const users = [{ name: 'Alice', age: 25 }, { name: 'Bob', age: 30 }];
    users.forEach(user => {
        console.log(`${user.name} is ${user.age} years old.`);
    });
    

    In this snippet, forEach() is used to log details about each user. This example demonstrates the utility of forEach() in handling arrays of objects for tasks such as generating reports or processing data.

Handling Asynchronous Logic

  1. Understand that forEach() is not suitable for handling promises directly due to its synchronous nature.

  2. Use Promise.all with map() for asynchronous operations instead.

    javascript
    const urls = ['url1', 'url2', 'url3'];
    const fetchPromises = urls.map(url => fetch(url));
    
    Promise.all(fetchPromises)
        .then(responses => responses.forEach(response => console.log(response.status)))
        .catch(error => console.error('Failed to fetch:', error));
    

    Here, for handling asynchronous operations, map() is used to create an array of Promises, and then Promise.all() is used to wait for all the Promises to resolve. After all promises resolve, forEach() is employed to handle each response effectively.

Conclusion

The forEach() method in JavaScript is a powerful tool for iterating over array elements and performing actions on them. It simplifies code and enhances readability by removing explicit loops and providing direct access to each element. Whether dealing with simple arrays or complex data structures, forEach() helps maintain clean and effective code. Utilize this method to streamline your array operations and improve the maintainability of your JavaScript code.