for…in Loop in JavaScript
In the previous articles, you've studied about the types of loops in JavaScript, which are -
There are few more types of loops which we'll be talking about in the upcoming articles.
Now, let's about the for…in loop in JavaScript which is a control flow statement that allows you to iterate over the properties of an object. It provides a convenient way to access each enumerable property of an object and perform operations on them.
It is particularly useful when working with objects, as it allows you to dynamically access and manipulate their properties. It iterates only over those keys of an object who have their enumerable property set to "true". The key values in an object have four attributes (value, writable, enumerable, and configurable).
Here's how the for...in loop works:
- The variable represents a different property name on each iteration of the loop. It is a variable that gets assigned to the name of each enumerable property of the object being iterated.
- The object is the object being iterated. It can be an array, an object literal, or any other object that has enumerable properties.
- The code block inside the loop is executed for each property in the object. You can access the value of the current property using the object[variable] syntax.
The syntax of for…in loop in JavaScript is -
for(variable in object){
//code
}
Example 1:
const book= {
book1: "Science",
book2: "Maths",
book3: "History",
};
for (let prop in book){
console.log(`${prop}: ${book[prop]}`);
}
book1: Science
book2: Maths
book3: History
Example 2:
const person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let prop in person) {
console.log(prop + ':', person[prop]);
}
name: John
age: 30
city: New York
Conclusion
To summarize, the for...in loop in JavaScript allows you to iterate over the enumerable properties of an object. It provides a convenient way to access and perform operations on each property. By understanding its syntax and usage, you can leverage the power of the for...in loop to manipulate objects in your JavaScript programs.