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![](https://ecs-static.teamtreehouse.com/assets/views/marketing/shared/community-banner-white-47072046c51352fe6a69f5e691ff5700b28bb11d45197d7bdf066d9ea3f72d0c.webp)
![Stephen Cole](https://secure.gravatar.com/avatar/c318b8e289f72d3e9b157df9785c598a?s=96&d=https%3A%2F%2Fecs-static.teamtreehouse.com%2Fassets%2Fcontent%2Fdefault_avatar-445fbbabfc8dc9188fb5967fe43322ee0c3e0dd1e10f378bf8343784af5a13eb.webp&r=pg)
Stephen Cole
Courses Plus Student 15,809 PointsUsing 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](https://uploads.teamtreehouse.com/production/profile-photos/11669503/micro_Bella_Bradbury_8x10a.jpg)
Bella Bradbury
Front End Web Development Techdegree Graduate 32,790 PointsA 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:
-
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.
-
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.
-
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!
Peter Huang
5,427 PointsPeter Huang
5,427 PointsGlad I saw this. helped me so much wondering the differences of these loops. God bless this answer
Samuel Kleos
Front End Web Development Techdegree Student 13,118 PointsSamuel Kleos
Front End Web Development Techdegree Student 13,118 PointsSuper helpful thank you!