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 Using `for in` to Loop Through an Object's Properties

the for ... in ... construct also works for arrays

You mentioned in the video that the "for... in" construct is available "only" for objects (with an emphasis on "only" which implies that it cannot be applied to arrays).

I tried the following in node REPL:

> l = [1,2,3,4];
[ 1, 2, 3, 4 ]
> for (var i in l) {console.log(i);}

It obviously works for arrays too.

Also, in one of the lessons about arrays you use the indexOf() method to check the existence of an element inside an array but I got the same results using the in construct:

// check if "bacon" is in shopping list
if ("bacon" in shoppingList) {
  // do something with bacon

Is there a cross-browser issue or some other corner case where these usage patterns do not apply?

2 Answers

I realised what I got wrong.

The for ... in construct (when used against arrays) loops through the indexes of the elements inside the array (which act like the keys inside an object). So one cannot use this construct the way I did in my previous example. The most one can do is something along these lines:

for (var i in someList) {console.log(someList[i]);}
Tiffany White
Tiffany White
5,373 Points

You can use for in for arrays as long as the order of the indexes doesn't matter. Check out MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in