Topic 33 of 87
for...in Loop
Overview
The for...in statement loops through the completely enumerable properties (keys) of an Object.
It is specifically designed to inspect the keys of objects. For each key, it executes the block of code, allowing you to access the key name and the corresponding value.
Syntax
Iterating an Object
javascript
const person = {
fname: "Kartik",
lname: "Rai",
age: 22
};
for (let key in person) {
// 'key' is the property name ("fname", "lname")
// person[key] gets the value
console.log(key + ": " + person[key]);
}Common Pitfalls
- Using
for...into iterate over an Array. While it technically works, it iterates over the array's index strings ('0', '1', '2'), not the values. Worse, it also iterates over any custom properties added to the Array prototype, and execution order is not guaranteed. Never usefor...inon arrays.
Interview Questions
Q:
What happens if you use
for...in on an array?A:
It will iterate over the array indices as strings (e.g., '0', '1', '2'), not the actual values. It is highly discouraged because it iterates over prototype properties as well.
Real-World Example
Iterating over a JSON configuration object to apply settings dynamically to an application.
example
javascript
for (let settingName in appConfig) {
applySetting(settingName, appConfig[settingName]);
}Check Your Knowledge
Test your understanding of for...in Loop with these quick questions.