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 Interacting with the DOM Traversing the DOM Getting All Children of a Node with children

Stephen Cole
PLUS
Stephen Cole
Courses Plus Student 15,809 Points

Using a for..of loop is cleaner.

Instead of using a for loop with a counter, I used a for...of loop instead:

for (let item of listItems) {
  attachRemoveButton(item);
};

It's cleaner and easier to read.

1 Answer

Bella Bradbury
seal-mask
.a{fill-rule:evenodd;}techdegree seal-36
Bella Bradbury
Front End Web Development Techdegree Graduate 32,790 Points

A for..of loop may look cleaner to you but it has a different meaning than a for loop! Here's the example array we'll use for the sake of simplicity because we can technically use for..in with arrays:

let arr = [5, 3, 78, 45, 312];

Our expanded array would look like this, with the left column being keys and the right being our values:

0 : 5
1 : 3
2 : 78
3 : 45
4 : 312

Let's break these two loops, and for..in, down really quick:

  1. for..in
    • This loop is specifically to get the keys only that are in a data structure.
    • This loop would only return the left column.
  2. for..of
    • This loop is specifically to get the only the values of the data in a structure.
    • This loop would only return the right column.
  3. for loop
    • This loop is very versatile comparably, you can change 3 different variables.
    • This loop also will return both keys and values, aka both of our columns.

Each of the three is great for their own unique reasons, so it's important to choose your for loop carefully so that it best serves you and your code!

Glad I saw this. helped me so much wondering the differences of these loops. God bless this answer