JavaScript - for...in in JavaScript

1. What is for...in in JavaScript?

The for...in loop is used to iterate over the enumerable property keys (or indexes) of objects and arrays.

  • When used with objects → it returns property names (keys).

  • When used with arrays → it returns indexes, not values.

  • It is not recommended for arrays if you want values directly. For that, use for...of instead.


2. Syntax

for (const key in object) {
    // Code to execute
}
  • key → Stores the current property name (or index).

  • object → The object or array you are looping through.


3. for...in with Objects ✅ (Best Use Case)

Example 1: Looping Through an Object

const person = {
    name: "John",
    age: 25,
    city: "New York"
};

for (const key in person) {
    console.log(`${key}: ${person[key]}`);
}

Output:

name: John
age: 25
city: New York
  • keyname, age, city

  • person[key]John, 25, New York


Example 2: Check Own Properties Only

for...in also loops through inherited properties, so we should use hasOwnProperty() to avoid unexpected results.

const person = Object.create({ gender: "male" });
person.name = "Alex";
person.age = 30;

for (const key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(`${key}: ${person[key]}`);
    }
}

Output:

name: Alex
age: 30

4. for...in with Arrays ⚠️ (Returns Indexes)

Example 1: Iterating Over an Array

const colors = ["red", "green", "blue"];

for (const index in colors) {
    console.log(`Index: ${index}, Value: ${colors[index]}`);
}

Output:

Index: 0, Value: red
Index: 1, Value: green
Index: 2, Value: blue
  • for...in gives indexes (0, 1, 2), not values directly.

  • Use colors[index] to access values.


Example 2: Why for...in Is Not Recommended for Arrays

const arr = ["apple", "banana"];
arr.extra = "mango";

for (const key in arr) {
    console.log(key);
}

Output:

0
1
extra
  • for...in loops over array indexes + custom properties.

  • This can cause bugs if you add extra properties to arrays.

Better option: Use for...of for array values.


5. for...in vs for...of

Feature for...in for...of
Iterates over Keys / Indexes Values
Works on objects ✅ Yes ❌ No
Works on arrays ⚠️ Yes (but gives indexes) ✅ Yes (gives values)
Recommended for Objects Arrays, Strings, Sets, Maps

Example: Comparing for...in vs for...of

const fruits = ["apple", "banana", "mango"];

// Using for...in (indexes)
for (const i in fruits) {
    console.log(`Index: ${i}, Value: ${fruits[i]}`);
}

// Using for...of (values)
for (const fruit of fruits) {
    console.log(`Value: ${fruit}`);
}

Output:

Index: 0, Value: apple
Index: 1, Value: banana
Index: 2, Value: mango

Value: apple
Value: banana
Value: mango

6. Key Takeaways

  • Use for...in for objects → gives keys.

  • Use for...of for arrays, strings, maps, sets → gives values.

  • Avoid using for...in on arrays unless you specifically need indexes.