In JavaScript, objects store and organize data in key-value pairs. Sometimes, the developers need to loop through each key-value pair. JavaScript provides a variety of loops, such as “for” or “forEach” loops, but they are used to iterate through arrays. For iterating through objects, the “for…in” loop is used, which iterates over an object’s properties.
This blog will illustrate the JavaScript for…in loop.
How to Use “for…in” Loops in JavaScript?
In JavaScript, the “for…in” loop is used to iterate over the object’s properties, including any enumerable properties of its prototypes. Every property and its value will be iterated over in the loop.
Syntax
For iterating JavaScript objects, use the following syntax of the for…in loop:
//...
}
Example
First, create an object of programming languages called “lang”:
HTML: 20,
CSS: 65,
JavaScript: 23,
NodeJS: 8
}
Now, print all the key-value pairs by iterating the object using for…in loop:
console.log(`${key}: ${lang[key]}`);
}
It can be seen that the for…in loop successfully iterated and printed all the key-value pairs on the console:
The for…in loop can be useful for iterating through the properties of an object, but it can also lead to unexpected behavior if the object has properties inherited from its prototypes. To avoid this, the best approach is to utilize the “Object.hasOwnProperty()” method inside the for…in loop to check if the property/attribute belongs to the object and not one of its prototypes.
Example
Iterate the object’s own properties using the hasOwnProperty() method:
if (lang.hasOwnProperty(key)) {
console.log(`${key} -> ${lang[key]}`);
}
}
You can also use “Object.keys()” or “Object.entries()” methods to get an array of the object’s own property names or key-value pairs, respectively, and then iterate over that array.
Conclusion
The “for…in” loop in JavaScript will iterate across all the enumerable attributes of an object, including those inherited through the prototype chain. The main problem with the for…in loop is that it iterates through the prototype chain’s properties. So, to avoid this use, the “Object.hasOwnProperty()” method inside the for…in loop. In this blog, we illustrated the usage of the for…in loop in JavaScript.