JavaScript for...in Loop

Iterating through object properties and array indexes

🗝️ What is a for...in Loop?

The for...in loop iterates through the properties of an object or the indexes of an array. It's perfect when you need to access property names or keys.


// Basic for...in syntax
for (let key in object) {
    // Access object[key]
}

// Example: Loop through object properties
const person = {
    name: "Alice",
    age: 25,
    city: "New York"
};

for (let property in person) {
    console.log(property + ": " + person[property]);
}
                                    

Output:

name: Alice
age: 25
city: New York

for...in Loop Use Cases

📦

Object Properties

Access all properties of an object

for (let key in obj) {
    console.log(key, obj[key]);
}
📋

Array Indexes

Get array indexes (not recommended)

for (let index in array) {
    console.log(index, array[index]);
}
🔍

Property Names

When you need the property names

for (let prop in settings) {
    console.log("Setting: " + prop);
}
🎯

Dynamic Access

Access properties dynamically

for (let key in data) {
    if (data[key] > 100) {
        console.log(key);
    }
}

🔹 for...in with Objects

The most common use of for...in is with objects:

🔸 Basic Object Iteration

// Simple object
const car = {
    brand: "Toyota",
    model: "Camry",
    year: 2022,
    color: "blue"
};

for (let property in car) {
    console.log(`${property}: ${car[property]}`);
}

Output:

brand: Toyota
model: Camry
year: 2022
color: blue

🔸 Object with Methods

// Object with properties and methods
const calculator = {
    result: 0,
    add: function(x) { this.result += x; },
    multiply: function(x) { this.result *= x; },
    display: function() { console.log(this.result); }
};

console.log("Properties and methods:");
for (let key in calculator) {
    console.log(`${key}: ${typeof calculator[key]}`);
}

Output:

Properties and methods:
result: number
add: function
multiply: function
display: function

🔸 Filtering Properties

// Only show non-function properties
const user = {
    name: "Bob",
    age: 30,
    email: "[email protected]",
    login: function() { console.log("Logged in"); },
    logout: function() { console.log("Logged out"); }
};

console.log("User data (properties only):");
for (let key in user) {
    if (typeof user[key] !== 'function') {
        console.log(`${key}: ${user[key]}`);
    }
}

Output:

User data (properties only):
name: Bob
age: 30

🔹 for...in with Arrays (Not Recommended)

While you can use for...in with arrays, it's usually not the best choice:

// for...in with array (returns indexes as strings)
const fruits = ["apple", "banana", "orange"];

console.log("Using for...in with array:");
for (let index in fruits) {
    console.log(`Index: ${index} (type: ${typeof index}), Value: ${fruits[index]}`);
}

console.log("\nBetter: Use for...of for array values:");
for (let fruit of fruits) {
    console.log(`Fruit: ${fruit}`);
}

console.log("\nBetter: Use regular for loop for indexes:");
for (let i = 0; i < fruits.length; i++) {
    console.log(`Index: ${i} (type: ${typeof i}), Value: ${fruits[i]}`);
}

Output:

Using for...in with array:
Index: 0 (type: string), Value: apple
Index: 1 (type: string), Value: banana
Index: 2 (type: string), Value: orange
Better: Use for...of for array values:
Fruit: apple
Fruit: banana
Fruit: orange
Better: Use regular for loop for indexes:
Index: 0 (type: number), Value: apple
Index: 1 (type: number), Value: banana
Index: 2 (type: number), Value: orange

🔹 Real-World Examples

Practical applications of for...in loops:

🔸 Configuration Settings

// Display all configuration settings
const config = {
    theme: "dark",
    language: "en",
    notifications: true,
    autoSave: false,
    maxFileSize: "10MB"
};

console.log("Current Settings:");
for (let setting in config) {
    console.log(`${setting}: ${config[setting]}`);
}

🔸 Form Data Processing

// Process form data
const formData = {
    firstName: "John",
    lastName: "Doe",
    email: "[email protected]",
    phone: "123-456-7890",
    newsletter: true
};

console.log("Form submission data:");
for (let field in formData) {
    if (formData[field]) { // Only show filled fields
        console.log(`${field}: ${formData[field]}`);
    }
}

🔸 Inventory Management

// Check inventory levels
const inventory = {
    apples: 50,
    bananas: 30,
    oranges: 0,
    grapes: 25,
    strawberries: 5
};

console.log("Low stock items (less than 10):");
for (let item in inventory) {
    if (inventory[item] < 10) {
        console.log(`${item}: ${inventory[item]} remaining`);
    }
}

Output:

Low stock items (less than 10):
oranges: 0 remaining
strawberries: 5 remaining

🔹 hasOwnProperty() Check

Use hasOwnProperty() to avoid inherited properties:

// Object with inherited properties
function Person(name, age) {
    this.name = name;
    this.age = age;
}

Person.prototype.species = "Homo sapiens";
Person.prototype.greet = function() {
    return `Hello, I'm ${this.name}`;
};

const john = new Person("John", 25);

console.log("All properties (including inherited):");
for (let prop in john) {
    console.log(`${prop}: ${john[prop]}`);
}

console.log("\nOwn properties only:");
for (let prop in john) {
    if (john.hasOwnProperty(prop)) {
        console.log(`${prop}: ${john[prop]}`);
    }
}

Output:

All properties (including inherited):
name: John
age: 25
species: Homo sapiens
greet: function() { return `Hello, I'm ${this.name}`; }
Own properties only:
name: John
age: 25

🔹 Best Practices

✅ When to Use for...in:

  • Object properties: When you need to iterate through object keys
  • Dynamic property access: When property names are unknown
  • Configuration objects: Processing settings or options
  • Form data: Iterating through form fields

❌ When NOT to Use for...in:

  • Arrays: Use for...of or regular for loop instead
  • When you need values only: for...of is better for values
  • Performance-critical code: Regular for loops are faster
  • When order matters: for...in doesn't guarantee order

💡 Tips:

  • Always use hasOwnProperty() to avoid inherited properties
  • Remember that for...in gives you keys/indexes, not values
  • Keys are always strings, even for arrays
  • Consider Object.keys() , Object.values() , or Object.entries() as alternatives

🧠 Test Your Knowledge

What does for...in loop give you when iterating through an object?