The for...in
loop in JavaScript is used to iterate over the enumerable properties of an object. It works well for objects but can also be used with arrays (though not recommended for arrays in most cases).
Syntax of for...in
for (variable in object) {
// Code to execute for each property
}
variable
: A variable that will hold the key or property name for each iteration.object
: The object whose properties will be iterated over.
Features of for...in
Iterates Over Properties
Thefor...in
loop retrieves the keys (property names) of an object.Enumerable Properties
It iterates over the properties of an object that are enumerable (can be listed).Can Access Both Keys and Values
You can use the key to access the corresponding value inside the loop.
Examples
1. Iterating Over an Object
const person = { name: "Junaid", age: 29, city: "Manmad" };
for (const key in person) {
console.log(key); // Outputs: name, age, city
console.log(person[key]); // Outputs: Junaid, 29, Manmad
}
2. Iterating Over an Array (Not Recommended)
When used on an array, for...in
iterates over the indices instead of values.
const fruits = ["apple", "banana", "cherry"];
for (const index in fruits) {
console.log(index); // Outputs: 0, 1, 2
console.log(fruits[index]); // Outputs: apple, banana, cherry
}
Best Practices for for...in
Use for Objects
for...in
is best suited for iterating over object properties.Avoid for Arrays
Usefor...of
or traditional loops (for
orforEach
) for arrays to avoid issues with inherited properties.
Comparison: for...in
vs for...of
Feature | for...in | for...of |
---|---|---|
Iterates Over | Keys (property names) | Values |
Use Case | Objects | Arrays, Strings, Maps, Sets, etc. |
Iterates Over Inherited Properties | Yes | No |
Works On | Objects, Arrays (not recommended) | Arrays, Strings, Maps, Sets, etc. |
Summary of Use Cases
Scenario | Recommended Loop |
---|---|
Iterating over object properties | for...in |
Iterating over array values | for...of |
Iterating over keys in arrays | for...in (not common) |
The for...in
loop is a powerful tool for iterating over the properties of an object in JavaScript. However, it should not be used for arrays due to potential issues with non-numeric keys and inherited properties. By combining for...in
with methods like Object.hasOwn()
, you can effectively and safely iterate over objects in your programs.