Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects Using `for in` to Loop Through an Object's Properties

When do we need to use for-in loop?

Hi guys, could you explain me better which is the difference between a normal loop and a for-in loop? It's difficult to understand which are the situations when to use one instead of the other one. Thanks for the clarification! Luca

Idan Melamed
Idan Melamed
16,285 Points

Hi Luca, I'm just taking this course as you, so I'm not sure my answer will be 100% correct.

A for loop looks like this:

for ( var i = 0; i  < 10; i += 1 ) {
};

In this example the loop will run exactly 10 times. So regular loops are great for when you know exactly how many times you need to run the through the loop. It is really good for going through arrays, because the first item in an array is array[0], the second item is array[1] and so on... And you can always use the 'length' property of an array to serve as your condition. Like this:

var squares = [1, 4, 9, 16, 25, 36];
for ( var i = 0; i < squares.length; i += 1 ) {
  console.log(squares[i])
}

The for...in loop goes through the properties of objects. For example, if you want to log all the values of:

var shoppingCart = { 
  size: 'small',
  color: 'green', 
  quantity: 17
 };

You can do it with:

for ( var prop in shoppingCart ) {
  console.log( shoppingCart[prop] );
}
'''

So regular for loops are great to use when you know exactly how many times you want to run it, and when you want to go through arrays.

For...in loops are great when you want to go through objects. You didn't even have to know how long the object is!

2 Answers

Steven Parker
Steven Parker
216,083 Points

Idan's right about for..in being handy for objects and properties. But it's also good for arrays.

For example, his array loop example that uses .length can be re-written this way:

var squares = [1, 4, 9, 16, 25, 36];
for ( var i in squares ) {
  console.log(squares[i]);
}

So I think it's always useful to use for... in loops, ins't it?