JavaScript For…In Loop – Iterate Over Object Properties
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
}
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]);
}
Output:
firstName: John lastName: Doe age: 30
Explanation:
- The loop iterates over each property in the
personobject, 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]);
}
Output:
0: Red 1: Green 2: Blue
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]}`);
}
Output:
brand: Toyota model: Corolla year: 2022
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]);
}
}
Output:
a: 1 b: 2
Explanation:
- The
hasOwnPropertymethod 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]}`);
}
}
Output:
name: Jane math: 90 science: 85
Explanation:
- The outer loop iterates over the
studentobject, and the inner loop iterates over thegradesobject.
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
}
Conclusion:
- The
for...inloop is ideal for iterating over the properties of objects. - For arrays,
for...ofor array-specific methods likeforEachare generally more appropriate. - Combining
for...inwithhasOwnPropertyensures that only the object’s own properties are considered.