Saturday, 25 January 2025

for-in Loop in JavaScript: A Beginner Guide to Iterating Over Object Properties

The for-in loop is a special type of loop in JavaScript used for iterating over the properties of an object. This loop iterates over all enumerable properties of an object that are keyed by strings.

Syntax

for (variable in object) {
    // code to be executed
}

 

·      variable: On each iteration, a different property name is assigned to this variable.

·      object: The object whose enumerable properties are iterated over.

 

printObjectProps.js

const person = {
    name: "Krishna",
    age: 35,
    city: "Bangalore"
};

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

Output

name: Krishna
age: 35
city: Bangalore

Iterating Over Arrays

Although for-in can be used to iterate over arrays, it is generally not recommended because it iterates over all enumerable properties, which may include unexpected properties or methods from the prototype chain. Instead, the for-of loop or traditional for loop should be used for arrays.

 

iterateOverArrays.js

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

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

Output

0: red
1: green
2: blue

Prototype Chain

The for-in loop also iterates over properties inherited through the prototype chain. To filter out these properties, you can use the hasOwnProperty method.

 

iterateOverPrototypeChain.js

const person = {
    name: "Krishna",
    age: 34
};

Object.prototype.country = "Bangalore"; // Adding a property to the prototype

console.log('Print all the properties of person object');
for (let key in person) {
    console.log(key + ": " + person[key]);
}

console.log('\nPrint all the properties of person object, and exclude prototype properties');
for (let key in person) {
    if (person.hasOwnProperty(key)) {
        console.log(key + ": " + person[key]);
    }
}

Output

Print all the properties of person object
name: Krishna
age: 34
country: Bangalore

Print all the properties of person object, and exclude prototype properties
name: Krishna
age: 34

Enumerability and Non-Enumerable Properties

In JavaScript, an enumerable property is a property of an object that can be iterated over in a for-in loop or when using methods like Object.keys(), Object.values(), and Object.entries().

 

enumerableProperties.js

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

Object.defineProperty(obj, 'c', {
    value: 3,
    enumerable: false
});

for (let key in obj) {
    console.log(key); // Only 'a' and 'b' will be logged
}

// Listing all enumerable properties
console.log(Object.keys(obj)); // ['a', 'b']

Output

a
b
[ 'a', 'b' ]

·      Enumerable Property: a and b are enumerable, so they are included in the for-in loop and Object.keys() output.

·      Non-Enumerable Property: c is non-enumerable, so it is not included in the for-in loop or Object.keys() output.

 

When to Use Enumerable vs. Non-Enumerable

1.   Enumerable Properties: Useful for properties that you want to expose and iterate over, such as user-defined attributes or configurations.

2.   Non-Enumerable Properties: Useful for internal state or implementation details that should not be exposed or iterated over, such as private data or methods that should not be exposed in loops.

 

Understanding and managing enumerable and non-enumerable properties helps control which properties are accessible during iterations and ensures that sensitive or implementation-specific properties are not exposed inadvertently.


 

Previous                                                    Next                                                    Home

No comments:

Post a Comment