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 trialSamuel Kleos
Front End Web Development Techdegree Student 13,581 PointsFor in loop vs for loop
I'm sorry so is it better to use a for loop and iterate through Object.keys(obj).length
since you can use the obj.prop
notation rather than the obj[prop]
notation in the for...in loop?
2 Answers
Bella Bradbury
Front End Web Development Techdegree Graduate 32,790 PointsHi Samuel!
To answer your question in a broader sense, let's have a quick recap of the loops from this lesson! There are many different parts that will determine what you decide to use but the biggest difference is how these loops return data. 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..of
, down really quick:
-
for..in
- This loop is specifically to get only the keys that are in a data structure.
- This loop would only return the left column.
-
for..of
- This loop is specifically to get 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 will return both keys and values, aka both of our columns.
There's really no right or wrong answer to your question. 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! The other difference in your question comes down to if you're looking to use quotations or not when declaring your property. It's very brief, but here's a short article about when it's better to not use/use quotations.
Hope this helps!
Steven Parker
231,269 PointsRegardless of loop type, you can only use the dot notation when the property name is already known. When getting property names from the object itself (by any method) you must always use the bracket notation to access them.
In case I'm misunderstanding, please show code examples.