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
Vic Mercier
3,276 PointsforEach method
When I used the forEach() method,I passed a callback function inside it and inside the callback function , my argument was element . What represent element,why do we use it and how does it work?
2 Answers
GREGORY ASSASIE
3,898 PointsThe forEach() method executes a provided function (that is the callback function) once for each element in the array.
YourARRAY.forEach(function callback(currentValue, index, array) { //your iterator }[ context]);
currentValue is the value of the current array element being iterated over index is the index of the currentValue array is the same array you called forEach on. context what you want the this key word to be.
Lexis Hanson
9,128 PointsThe argument you pass in to the callback is representingg each element (or item) you are iterating over to the left of the forEach method. In this case, for an array ['blue', 'red', 'orange'], "element" will refer to blue, then red, then orange.
var array = ['blue', 'red', 'orange']
array.forEach(element => console.log(element));
// blue red orange