DEV Community

Bogdan Varlamov
Bogdan Varlamov

Posted on

JavaScript Array Methods: Understanding `forEach`

JS Array method: .forEach()

JavaScript provides several methods to work with arrays, one of which is forEach. This method is a modern alternative to the traditional for loop, offering a more straightforward way to iterate over each item in an array.

Basic Example

Consider the following array of fruits:

const fruits = ['apple', 'mango', 'avocado']
fruits.forEach((fruit, index) => {
  console.log(fruit) // 'apple', 'mango', 'avocado'
  console.log(index) // 0, 1, 2
})
Enter fullscreen mode Exit fullscreen mode

In each iteration of forEach, a callback function is executed that takes the current item (in this case, the name of a fruit) as its first argument. The callback function can also take a second argument, index, which represents the position of the current item in the array. For example, the first fruit ('apple') will have an index value of zero.

This method is particularly useful when you need to iterate over an array of items and perform operations using the data within this array.

Practical Example

Imagine we have an array outOfProducts indicating items that are currently out of stock. We want to update the data in our app to no longer display these items to users until we receive a new supply. We can accomplish this with the forEach method by setting the inStock property to false for each out-of-stock product in our products object.

const products = {
  apple: { price: 4, inStock: true },
  avocado: { price: 12, inStock: true },
  mango: { price: 9, inStock: true },
  cucumber: { price: 10, inStock: true },
  tomato: { price: 6, inStock: true },
}

const outOfProducts = ['apple', 'mango', 'avocado']

outOfProducts.forEach((fruit) => {
  products[fruit].inStock = false
})

console.log(products)
/*
Console.log will output updated products object:

{
    apple: { price: 4, inStock: false },
    avocado: { price: 12, inStock: false },
    mango: { price: 9, inStock: false },
    cucumber: { price: 10, inStock: true },
    tomato: { price: 6, inStock: true },
}
*/
Enter fullscreen mode Exit fullscreen mode

By using the forEach method, we can easily iterate over the outOfProducts array and update our products object accordingly. This method makes it easier to work with arrays and change data based on what's in those arrays.

https://bgdnvarlamov.com/blog/array-method-forEach

Top comments (0)