Introduction
Being able to loop over items in an array is a crucial skill to understand as a developer. A great way to do just that is by using a popular JavaScript array method; forEach
. This method allows you to loop over array items with a very clean, simple syntax. Let’s take a look.
Before getting started, if you need a refresher on JavaScript basics, checkout our full course here:
https://teamtreehouse.com/library/javascript-basics
Consider the following code:
const users = ['John', 'Sarah', 'Jamie'];
We have an array named users
and inside of this array we have a few strings. If we wanted to log all these strings to the console, we could write something like this:
console.log(users[0]);
console.log(users[1]);
console.log(users[2]); // output: 'John'
// output: 'Sarah'
// output: 'Jamie'
While that works just fine, there is a much better way. What if our array had hundreds of strings? This is where loops come in. Let’s see how we can log our users
array items to the console using a standard for
loop:
for (let i = 0; i < users.length; i++) { console.log(users[i]);
} // output: 'John'
// output: 'Sarah'
// output: 'Jamie'
As you can see, the for
loop works just fine but how can we convert this to use the forEach
method instead? Well, because forEach
is an array method, we can just write our array method and use dot notation to chain on our method like this:
users.forEach()
Now, lets go over the parameters we can use with this method. The first parameter I want to go over is just the callback function. This is the bit of logic that we want to run each time through the loop.
users.forEach( () => { // write logic here
});
You can give this callback function some parameters as well. The first one we’ll cover is the element parameter. This parameter essentially holds the value of the element currently being processed. So the first time through the loop, this will be the array’s first element. Then the second time through the loop, it’ll be the array’s second element and so on and so on. You can name this element parameter anything you’d like. I personally try to name my arrays a plural word since it holds a collection of items and then when I run the forEach method, I set my element parameter to the singular version of that word. Check out these examples:
users.forEach( (user) => { // write logic here
}); colors.forEach( (color) => { // write logic here
}); developers.forEach( (developer) => { // write logic here
});
Lets take one of those examples above and console.log the value of our element parameter.
const users = ['John', 'Sarah', 'Jamie']; users.forEach( (user) => { console.log(user);
}); // output: 'John'
// output: 'Sarah'
// output: 'Jamie'
As you can see, this works exactly the same as our for
loop we wrote earlier but with a much easier, simple syntax.
Now, let’s talk about the index
parameter. This parameter is the index of the currentelement
being processed. So let’s add this parameter to the above code and then run a console.log
on it to see what is returned to us.
const users = ['John', 'Sarah', 'Jamie']; users.forEach( (user, index) => { console.log(user); console.log(index);
}); // output: 'John'
// output: 0 // output: 'Sarah'
// output: 1 // output: 'Jamie'
// output: 2
So what’s happening here is each time through the loop, user
(our element parameter) holds the value of an array element. That array element’s index is stored in that index
parameter. Just like the element
parameter, you can name this index
parameter anything you’d like but it is usually just named index
.
Practice forEach
Below are some small snippets of code using the forEach
method and its parameters:
const developers = [ { name: "John Smith", favoriteLanguage: 'JavaScript', languages: ['JavaScript', 'Python'], }, { name: "Sarah Johnson", favoriteLanguage: 'CSS', languages: ['HTML', 'CSS', 'JavaScript'], }
]; developers.forEach((developer) => { console.log(developer.name);
}); // output: 'John Smith'
// output: 'Sarah Johnson' developers.forEach((developer) => { console.log(developer.languages);
}); // output: (2)['JavaScript', 'Python']
// output: (3)['HTML', 'CSS', 'JavaScript']
<ul> <li>Red</li> <li>Green</li> <li>Blue</li>
</ul> const colors = document.querySelectorAll('li'); colors.forEach((color, index) => { color.addEventListener('click', () => { console.log(`${index}: ${color.textContent}`); });
}); /*
The webpage holds an unordered list with list items containing colors. Clicking on a color will output this in the console respectively:
*/ // clicking "Red" will output: 0: Red
// clicking "Green" will output: 1: Green
// clicking "Blue" will output: 2: Blue
Final Thoughts
I hope this guide on using the forEach
method was helpful! This JavaScript iteration method is a great tool in your JavaScript arsenal. Looping over data will come in handy many times throughout your developer journey.
New to JavaScript or need a refresher? Checkout this JavaScript basics course where we cover all the basics including arrays:
https://teamtreehouse.com/library/javascript-basics