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

Joseph Bertino
seal-mask
.a{fill-rule:evenodd;}techdegree
Joseph Bertino
Full Stack JavaScript Techdegree Student 14,652 Points

Alternative 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
STAFF
Robert Manolis
Treehouse Guest Teacher

Hi Joseph Bertino, give this a try. :thumbsup:

[...list].forEach((listItem, index, list) => { console.log(listItem, index, list); });
Joseph Bertino
seal-mask
.a{fill-rule:evenodd;}techdegree
Joseph Bertino
Full Stack JavaScript Techdegree Student 14,652 Points

Note: 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
Robert Manolis
Treehouse Guest Teacher

Hey 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.