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 trialJoseph Bertino
Full Stack JavaScript Techdegree Student 14,652 PointsAlternative to for() loops?
I know this is JavaScript (lol), but personally I think using the for() loop to iterate through a list as we have been doing is both clunky and ugly, and I prefer a more "Pythonic" way of iterating through a list.
So I've been using the following one-liner:
Array.prototype.forEach.call(list, listElem => { <do something with listElem>; });
Is there a better alternative to this approach that avoids the for loop entirely and is still succinct?
2 Answers
Robert Manolis
Treehouse Guest TeacherHi Joseph Bertino, give this a try.
[...list].forEach((listItem, index, list) => { console.log(listItem, index, list); });
Joseph Bertino
Full Stack JavaScript Techdegree Student 14,652 PointsJoseph Bertino
Full Stack JavaScript Techdegree Student 14,652 PointsThis is great, Robert! Nice to see the spread operator in action.
Joseph Bertino
Full Stack JavaScript Techdegree Student 14,652 PointsJoseph Bertino
Full Stack JavaScript Techdegree Student 14,652 PointsNote: When playing around in a workspace, I even got this to work without the spread operator
list.forEach((listItem, index, list) => { console.log(listItem, index, list); });
Robert Manolis
Treehouse Guest TeacherRobert Manolis
Treehouse Guest TeacherHey Joseph Bertino, yeah, if you're working with a collection that allows for the use of array methods, then you won't need the spread operator.
For example, if you use the getElementsByTagName or getElementsByClassName methods, they return an HTMLcollection, which won't work with those higher order functions like
.forEach()
. So to use forEach on an HTMLcollection, you need to first turn the collection into an array.But if you use the querySelectorAll method, you get back a NodeList instead, and you can use
.forEach()
directly on a NodeList without the spread operator.