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

Different solution to accessing an array of Objects?

HI!,

I noticed in the video tutorial: https://teamtreehouse.com/library/javascript-loops-arrays-and-objects/tracking-data-using-objects/the-build-an-object-challenge-part-2-solution Dave used a normal for loop for accessing his array. I however used a for/in loop to do the same. Are there any adverse effects to programming this way? Should I follow his steps carefully or should I be more pragmatic?

3 Answers

Steven Parker
Steven Parker
243,318 Points

My opinion is that "for...in" loops are perfectly legitimate for arrays.

Adding a property to an array is not something that is likely to occur by accident, nor is it something I would want to allow to persist if it did. I would welcome any error it caused and immediately fix the problem.

The flip side to Thomas' argument is that "for...in" loops are very useful for iterating any kind of list object, including simple arrays. What he refers to as a "regular" for loop would only return items for which the keys (indexes) are known. It's easy to overlook things that way. In the above example. for instance, the modified array has 4 items accessible with the for...in loop, but arr.length will still return "3".

My bottom line: For simple arrays it makes no difference. For complex list objects you should know what you're doing and choose the method accordingly.

Don't use for..in when iterating over arrays.

Arrays are objects, which means you can access properties.

var arr = ['person 1', 'person 2', 'person 3'];

for(a in arr) {
    console.log(a + ': ' + arr[a]);
}

If I were to add a property to the Array.prototype at the beginning of the example above like this:

Array.prototype.customValue = 100;

This will also be outputted in the console.log, which will be unexpected, and probably not what you want.

Bottom line;

Just use regular for loops (at least when using arrays)

Thomas raises good points. On top of that advice, I would say as soon as you have a grasp on looping in js, learn lodash. It is a widely used, convenient library with all kinds of methods for dealing with objects, arrays, numbers, etc. I haven't written a for loop in months. ES6 will incorporate a lot of lodash-esque features as well.