JavaScript JavaScript and the DOM Responding to User Interaction Listening for Events with addEventListener()

Adam Lyles Kauffman
Adam Lyles Kauffman
11,732 Points

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
172,127 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().