Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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,592 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
Bella Bradbury
Web Development Techdegree Student 14,361 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