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

can i use "For In" loops on JavaScript Arrays as well as objects?

Dave McFarland , et al.,

In the Objects section of your JavaScript Loops, Arrays & Objects modules, you introduce the "For In" loop to iterate through Objects. i believe this same method exists to loop through JavaScript Arrays, aslo, is that correct?

best,

— faddah portland, oregon, u.s.a.

2 Answers

Hi Faddah Wolf! It certainly is possible, although if you care about ordering though (which is usually the argument for placing items into an array in the first place), you'll need to make a for loop that iterates through the indexes. From the MDN documentation: "Because the order of iteration is implementation-dependent, iterating over an array may not visit elements in a consistent order. Therefore it is better to use a for loop with a numeric index (or Array.prototype.forEach() or the for...of loop) when iterating over arrays where the order of access is important."

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in

thanks! can you give an example, Stephen Gheysens , as to the differences in results? how can it not iterate over the array in order (i'm assuming, array indices 0, 1, 2, ...etc.)?

best,

— faddah portland, oregon, u.s.a.

So I'll admit can't actually find the source of the "difference in results" claim (I even just tried reading through the ECMAScript definitions of array iterators). I've read in many places (like here and here) that the it's bad practice because the elements aren't guaranteed to come out in order - I've always assumed they meant that the order the array elements are captured won't necessarily mirror the indexed order.

That aside, one prominent issue arises when the Array class has been extended with prototypal inheritance. For a clear explanation of Prototypal Inheritance, I'll leave it up to Andrew Chalkley https://teamtreehouse.com/library/objectoriented-javascript#prototypal-inheritance

thank you! i will check Andrew Chalkley's article.

best,

— faddah

 portland, oregon, u.s.a.