JavaScript JavaScript Loops, Arrays and Objects Tracking Data Using Objects The Build an Object Challenge, Part 2

Adrian Thomas
Adrian Thomas
1,572 Points

For loops vs For In loops for Objects. When would you use one over another?

When it comes to objects, when would a person opt to use a for loop than the for-in loop?

As far as I can tell, they both perform the same action minus the need to specify the '.length' property and have to increment by using i += 1 or i++.

Just seems like a few keystrokes saved but I wonder if there are any values or gotchas to watch out for when it comes to using one loop or the other.

Any thoughts?

1 Answer

Steven Parker
Steven Parker
177,495 Points

The conventional for loop is good when you need a numeric index for calcuations, or when the order of access is important, or when you want to limit the loop to only those items that have an index that is a number.

The for...in loop is good for looping through the enumerable properties of an object when the order is not important, and when the property names are not all numbers.

In short:
    for         :point_left: collection elements, sequential order, numeric keys/indexes only
    for..in :point_left: enumerable properties, arbitrary order, any keys/indexes

Adrian Thomas
Adrian Thomas
1,572 Points

Make sense. Thanks for the explanation.