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 JavaScript and the DOM (Retiring) Responding to User Interaction Listening for Events with addEventListener()

help Redoing loop

i had a hard time understanding how to set up for.. each loops and for.. of loops. can someone please redo the for loop which iterates over the array of list items with a for.. each and for.. of. Also a for.. in loop wouldn't be possible because it is for object properties right? thanks for the help in advance!

1 Answer

Steven Parker
Steven Parker
231,269 Points

Here's four different types of iteration (and "for...of" can be used even though it's better suited for objects):

for (let i = 0; i < listItems.length; i += 1) {  // original loop, iterates index
  console.log(listitems[i]);
}
for (let i in listItems) {      // this iterates properties
  console.log(listitems[i]);    // which for arrays will seem like indexes
}
for (let item of listItems) {   // this iterates through the items themselves
  console.log(item);
}
listItems.forEach(item => {     // this also works directly on the items
  console.log(item);
});

Note that "forEach" is actually an array method and not a loop statement. And there are some other differences as well. Like "for...in" iterates strings and not numbers. For more details, see the MDN pages on for, for..in, for...of, and forEach().