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!
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
Robert Mews11,540 Points
For and For in loops - Arrays and Objects?
This is my future self going back trying to get clarity around for and for in loops for mixing arrays and objects.
It seems you'd use a for loop if you have objects inside an array, but use a for in loop if you have an array inside an object. Does anyone have a clear way to explain why?
Sam Shiffman7,466 Points
This is a very simplistic explanation, but that's because I understand the difference between for and for/in at a very superficial level :-)
A 'for' loop gives you the a pretty open framework to iterate over the array in steps from beginning to end, a portion of the array, or skipping (i = 0; i < array.length; i += 2). You don't need to iterate over every index (analagous to 'property' of an object), just the ones you select when setting up the range in the for statement. But in any case, an array's properties (or "indices") are numbered from 0 to whatever. And each of the elements in the array can be numbers, strings, arrays, objects or functions.
A 'for/in' loop is meant to iterate over EVERY property in the object, which usually has very different names for each property, such as "firstName", "lastName", "email", "city", etc. And the value associated with each property in the object can be a number, string, array, object, or function.