JavaScript Array .forEach() method

The array .forEach() is one of the iterative methods in Javascript where it loops on each and every item of the array. However, it does not return anything and skips array item that is empty.

It is important to note as well that you cannot stop the forEach() loop from executing the rest of the array items. You cannot break outside of the loop unless you throw an error or exception. It will excute the iteration on each array item and it does not wait for Promises as well because it does not cater async operations.

Array .forEach() Method Syntax

This is how you can use the the .forEach() method.


  array.forEach((item, index, arrayCopy) => {
    // your code goes here...
  }, thisArg)

Callback Function Inside the callback function, it contains three parameters:
  • item - The current iterated item in the array.
  • index The current index of the current item.
  • arrayCopy - The copy of the reference array that you can use within the callback function
thisArg optionalRefers to the this value when calling the callback function.

Array .forEach() Method Examples

To elaborate more how the .forEach() works, let's run two examples.

1. Let's say we have an array of objects where the data is inspired by One Price anime. Each array item, which is an object, contains name, favoriteFruite and emoji. Somehow with an imaginary use case, we want to display each of the items in a format like this - Nami likes to eat watermelon 🍉.

For that reason, where we just want to iterate the array and display some results, we are not returning anything, an array .forEach() method is a compatible solution.

  
    const ladies = [
      { name: "Nami", fruit: "Watermelon", emoji: "🍉", },
      { name: "Robin", fruit: "Avocado", emoji: "🥑", },
      { name: "Boa", emoji: "🍓", fruit: "Strawberry", },
    ]

    ladies.forEach(({ name, emoji, fruit}) => {
      console.log(`${name} likes ${emoji} ${fruit}`)
    });
  

The output for this code in the console would be like this:

  
    Nami likes 🍉 Watermelon
    Robin likes 🥑 Avocado
    Boa likes 🍓 Strawberry
  

2. This second example is one of the common real-world use cases of a forEach() method. So let's say we have a multiple div elements with each a class of .card. Now, we want to listen for a click event on that card and do something when a specific card is clicked.

This is how you can use .forEach() method to listen for a click event on multiple elements or targets.

  
    const cards = document.querySelectorAll(".card");

    cards.forEach((card, index) => {
      card.addEventListener("click", () => {
        // implement your logic here ...
      })
    })
  

Watch Tutorial

For a more clearer examples and details about Javascript array forEach() method, check out this video on YouTube.