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 trialStephen 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
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,307 PointsSamuel Kleos
Front End Web Development Techdegree Student 13,307 PointsSuper helpful thank you!