Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript Array Iteration with a For Loop

Daniele Fusari
Daniele Fusari
40,669 Points

.forEach loop

Just wondered how you would use the .forEach loop on this.

I get the for loop

 for (let i=0; i < myRandomList.length; i++) {
  console.log('Item ' + i + ' in the array is ' + myRandomList[i]);
}

How do I get the forEach loop to go through each item in the array, dont have an i counter

myRandomList.forEach(function (){
  console.log('The number is ' + myRandomList.forEach() ); ???
});

1 Answer

Chris Shaw
Chris Shaw
26,676 Points

Hi Daniele Fusari,

The forEach method supplies 3 parameters that we can make use of which are currentValue, index and array (meaning the current array). What this means is rather than needing to know the index we can simply access the current value in the iterator and we will get the same result as we do in your first example.

myRandomList.forEach(function(listItem, index) {
  console.log('Item ' + index + ' in the array is ' + listItem);
});

Pretty cool right?

You can read a heap more about forEach on MDN.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach

Happy coding!