#1 .forEach()

The .forEach() method comes in handy when you want to manipulate some data but you don’t need to return any data. All this method does is executes a function (that you provide) once for each element in an array.

Use Case

We have four buttons on a page. We need to attach an event listener to all of the buttons to make some jazz happen when one is clicked.

We will need to grab those buttons on the page and send them through .forEach() to solve our problem. Using the .querySelectorAll() method returns us a NodeList which we will treat just like an array. We store that NodeList into a variable so we can send it through the .forEach() method.

We cycle over each button in the array and add an event listener to each button that logs the button at a particular index when clicked. That was pretty easy and of course you’ll want to do something cooler than logging the index to the console.