Adrian Thomas1,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
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.
Steven Parker200,540 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.
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.
for collection elements, sequential order, numeric keys/indexes only
for..in enumerable properties, arbitrary order, any keys/indexes