JavaScript for…in Loop

The for...in loop in JavaScript is used to iterate over the enumerable properties of an object. It allows you to access the keys (or property names) of an object, which can then be used to get the corresponding values.

1. Syntax of for...in Loop:

for (key in object) {
    // Code to be executed
}

Try It Now

Explanation:

  • key: A variable that stores the current property’s key on each iteration.
  • object: The object whose properties are being iterated over.

 

2. Basic Example of for...in Loop:

let person = {
    firstName: "John",
    lastName: "Doe",
    age: 30
};

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

Try It Now

Output:

firstName: John
lastName: Doe
age: 30

Try It Now

Explanation:

  • The loop iterates over each property in the person object, printing both the key and its corresponding value.

 

3. Iterating Over Arrays with for...in:

Though for...in can be used to iterate over arrays, it is not recommended because it iterates over all enumerable properties, including those that are not array elements.

 

let colors = ["Red", "Green", "Blue"];

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

Try It Now

Output:

0: Red
1: Green
2: Blue

Try It Now

Note: Use for...of or array iteration methods (like forEach) for better performance and clarity when working with arrays.

4. Enumerating Properties in Objects:

The for...in loop is particularly useful for iterating over properties in an object.

let car = {
    brand: "Toyota",
    model: "Corolla",
    year: 2022
};

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

Try It Now

Output:

brand: Toyota
model: Corolla
year: 2022

Try It Now

5. Checking for Object’s Own Properties:

To avoid iterating over inherited properties, use hasOwnProperty method inside the loop.

let obj = { a: 1, b: 2 };

Object.prototype.c = 3; // Adding an inherited property

for (let key in obj) {
    if (obj.hasOwnProperty(key)) {
        console.log(key + ": " + obj[key]);
    }
}

Try It Now

Output:

a: 1
b: 2

Try It Now

Explanation:

  • The hasOwnProperty method ensures that only the object’s own properties are logged, excluding inherited properties.

6. Iterating Over Nested Objects:

let student = {
    name: "Jane",
    grades: {
        math: 90,
        science: 85
    }
};

for (let key in student) {
    if (typeof student[key] === 'object') {
        for (let subKey in student[key]) {
            console.log(`${subKey}: ${student[key][subKey]}`);
        }
    } else {
        console.log(`${key}: ${student[key]}`);
    }
}

Try It Now

Output:

name: Jane
math: 90
science: 85

Try It Now

Explanation:

  • The outer loop iterates over the student object, and the inner loop iterates over the grades object.

7. for...in vs for...of:

  • for...in: Iterates over the keys of an object.
  • for...of: Iterates over the values of an iterable (like arrays or strings).

Comparison Example:

let array = ["A", "B", "C"];

for (let index in array) {
    console.log(index); // Outputs indices: 0, 1, 2
}

for (let value of array) {
    console.log(value); // Outputs values: A, B, C
}

Try It Now

Conclusion:

  • The for...in loop is ideal for iterating over the properties of objects.
  • For arrays, for...of or array-specific methods like forEach are generally more appropriate.
  • Combining for...in with hasOwnProperty ensures that only the object’s own properties are considered.