Course contentsShow
← JavaScript
Lesson 356 of 2,72310. LoopsFree lesson

For...in with Arrays: Why to Avoid

Understand why for...in is problematic with arrays and when to use for...of instead.

For...in with Arrays: Why to Avoid

You'll learn why using for...in with arrays can cause unexpected bugs and when to reach for for...of instead.

Why For...in Is Problematic with Arrays

While for...in technically works with arrays, it's designed for objects and causes subtle problems. Here's why:

It iterates over property names, not just array elements. If someone adds a custom property to an array (arrays are objects, after all), for...in will include it. You'll get all enumerable properties, not just the numeric indices you expect.

The loop variable is a string, not a number. Even when iterating array indices, for...in gives you "0", "1", "2" as strings. This can break calculations or cause type coercion issues.

Order is not guaranteed. While most engines iterate arrays in order, the JavaScript specification doesn't guarantee it for for...in.

The Safer Alternative: For...of

Think of it this way: for...in asks "what properties does this object have?" while for...of asks "what values does this collection contain?" For arrays, you almost always want the second question.

const colors = ['red', 'green', 'blue'];
colors.custom = 'extra property';

// BAD: for...in includes the custom property
for (let key in colors) {
  console.log(key); // "0", "1", "2", "custom" — unwanted!
}

// GOOD: for...of only iterates array values
for (let color of colors) {
  console.log(color); // "red", "green", "blue" — exactly what we want
}

Key Takeaway: Avoid for...in with arrays—it includes extra properties and gives you string keys. Use for...of to safely iterate array values, or stick with a traditional for loop when you need index control.