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 JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2

Adrian Thomas
Adrian Thomas
1,572 Points

For loops vs For In loops for Objects. When would you use one over another?

When it comes to objects, when would a person opt to use a for loop than the for-in loop?

As far as I can tell, they both perform the same action minus the need to specify the '.length' property and have to increment by using i += 1 or i++.

Just seems like a few keystrokes saved but I wonder if there are any values or gotchas to watch out for when it comes to using one loop or the other.

Any thoughts?

1 Answer

Steven Parker
Steven Parker
231,269 Points

The conventional for loop is good when you need a numeric index for calcuations, or when the order of access is important, or when you want to limit the loop to only those items that have an index that is a number.

The for...in loop is good for looping through the enumerable properties of an object when the order is not important, and when the property names are not all numbers.

In short:
    for         :point_left: collection elements, sequential order, numeric keys/indexes only
    for..in :point_left: enumerable properties, arbitrary order, any keys/indexes

Adrian Thomas
Adrian Thomas
1,572 Points

Make sense. Thanks for the explanation.