DEV Community

Muhammad Rizwan Ashiq
Muhammad Rizwan Ashiq

Posted on • Updated on

Array.forEach() Method

What is ForEach Function?

The forEach() method is a method that is used to iterate over the elements of an array. It takes a callback function as an argument, and the callback function is called for each element in the array.

Syntax

Here's the syntax for using forEach():

arr.forEach((element, index, array) => {
    // Do something with element
});
Enter fullscreen mode Exit fullscreen mode

The callback function is invoked with three arguments:

  • element: the current element being processed in the array
  • index (optional): the index of the current element
  • array (optional): the array that forEach() is being called on

The callback function is executed for each element in the array, in ascending order.

Here's an example of how to use forEach() to print all the elements of an array to the console:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach(function (number) {
    console.log(number);
});

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

I prefer arrow functions in array functions because of cleaner syntax

array.forEach(item => {}) instead of array.forEach(function (item) {})

Both are OK, it's totally upto you what you prefer

You can also use an arrow function as the callback, like this:

numbers.forEach((number) => console.log(number));
Enter fullscreen mode Exit fullscreen mode

In the examples above, the callback function logs each element of the numbers array to the console. The callback function takes a single argument, which is the current element being processed.

You can also pass the index of the current element and the array itself as arguments to the callback function. Here's an example that prints both the element and its index:

numbers.forEach(function (number, index, array) {
    console.log(index + ": " + number);
});

// Output:
// 0: 1
// 1: 2
// 2: 3
// 3: 4
// 4: 5
Enter fullscreen mode Exit fullscreen mode

The forEach() function does not return a value. It simply executes the callback function for each element in the array.

ForEach vs For Loop

The forEach() method is similar to the for loop. The main difference is that the for loop can be used to iterate over any type of collection, not just arrays. The forEach() method is only used to iterate over arrays.

Here's an example of how to use a for loop to iterate over an array:

const numbers = [1, 2, 3, 4, 5];

for (let i = 0; i < numbers.length; i++) {
    console.log(numbers[i]);
}

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

Here's an example of how to use forEach() to iterate over an array:

const numbers = [1, 2, 3, 4, 5];

numbers.forEach((number) => console.log(number));

// Output:
// 1
// 2
// 3
// 4
// 5
Enter fullscreen mode Exit fullscreen mode

When to use forEach()?

The forEach() method is useful when you want to iterate over an array and perform some action on each element. It's a cleaner way to write a for loop.

Example

Here is an example of how you might use the forEach() function in the context of an e-commerce website.

Imagine that you have an array of products, and each product is represented by an object with the following properties:

  • id: the unique ID of the product
  • name: the name of the product
  • price: the price of the product
  • quantity: the number of units in stock

You can use the forEach() function to iterate over the array of products and perform some action on each product.

Example 1: Displaying total price of all products

You might want to calculate the total value of all the products in stock. You can do this by using the forEach() function to sum the price of each product multiplied by its quantity.

Here's the code that does this:

const products = [
    { id: 1, name: "Product 1", price: 10, quantity: 5 },
    { id: 2, name: "Product 2", price: 15, quantity: 2 },
    { id: 3, name: "Product 3", price: 20, quantity: 3 },
];

let totalValue = 0;

products.forEach((product) => {
    totalValue += product.price * product.quantity;
});

console.log(totalValue); // prints 105 (10 * 5 + 15 * 2 + 20 * 3)
Enter fullscreen mode Exit fullscreen mode

Example 2: Apply 10% discount to all products having quantity > 3.

Here's the code that does this:

products.forEach((product) => {
    if (product.quantity > 3) {
        product.price *= 0.9; // apply 10% discount
    }
});
Enter fullscreen mode Exit fullscreen mode

Now the products array will contain the modified objects.

[
    { id: 1, name: "Product 1", price: 10, quantity: 5 },
    { id: 2, name: "Product 2", price: 15, quantity: 2 },
    { id: 3, name: "Product 3", price: 18, quantity: 3 },
];
Enter fullscreen mode Exit fullscreen mode

Example 3: Removing an object from the array

We can also use the forEach() function to remove elements from an array. For example, you might want to remove all the products that have a quantity of 0.

Here's the code that does this:

products.forEach((product, index, array) => {
    if (product.quantity === 0) {
        array.splice(index, 1);
    }
});
Enter fullscreen mode Exit fullscreen mode

Now the products array will contain the modified objects.

[
    { id: 1, name: "Product 1", price: 10, quantity: 5 },
    { id: 2, name: "Product 2", price: 15, quantity: 2 },
    { id: 3, name: "Product 3", price: 18, quantity: 3 },
];
Enter fullscreen mode Exit fullscreen mode

All done! 🎉 Quick recap:

The forEach() function is useful for iterating over an array and performing some action on each element. It is similar to the for loop, but it is more concise and easier to read.

forEach() is not supported by Internet Explorer (which most of the user doesn't use anymore). If you need to support older browsers, you can use a for loop or the forEach() function from a polyfill library like Array.prototype.forEach.

Top comments (0)