DEV Community

Cover image for Learn how to use the forEach method in JS!
Ustariz Enzo
Ustariz Enzo

Posted on • Updated on

Learn how to use the forEach method in JS!

Hey fellow creators,

The forEach method is really handy when you’re working with arrays or nodelists.
It allows you to run a callback function for each element in those containers.
Let’s learn how to use it in less than a minute!

If you prefer to watch the video version, it's right here :

1. How to use it.

To use it, you need to feed it with a callback function, which can take up to three parameters.
Those parameters are:

  • The current value
  • The index
  • And the array/nodelist that you’re working with.


const array = [1, 2, 3];

array.forEach((current, index, arr) => {
    console.log(current, index, arr);
});


Enter fullscreen mode Exit fullscreen mode

Take a look in your console/terminal and you’ll see:
image of console

2. Let’s create three buttons to have a real example.

In an HTML file, create three buttons:



<button data-action="modify">Modify</button>
<button data-action="delete">Delete</button>
<button data-action="update">Update</button>


Enter fullscreen mode Exit fullscreen mode

In your JS file, select the buttons:



const buttons = document.querySelectorAll('button'); 


Enter fullscreen mode Exit fullscreen mode

The .queryAll method returns a nodelist, and the nodelists also have access to the forEach method in their prototype.

Thus, we can use it to attach an event listener to each button :



buttons.forEach(btn => {
    btn.addEventListener('click', (e) => {
        alert(e.target.getAttribute
        ('data-action'))
    })
});


Enter fullscreen mode Exit fullscreen mode

This is a basic example but you now know how useful this method is!
You can easily avoid code repetition.

Come and take a look at my Youtube channel: https://www.youtube.com/c/TheWebSchool

See you soon!

Enzo.

Top comments (0)