The for...in
loop in JavaScript is used to iterate over the properties of an object. This loop scans all the properties of an object and returns each property one by one. It’s important to note that the properties are unordered, so the order of object properties is not guaranteed. Here’s how to use the for...in
loop along with example code snippets:
Usage of the for…in Loop
for (let key in object) {
// Operations for each property go here
}
In the structure above, key
represents each property of the object, and object
refers to the object being iterated. The loop enters each property and performs the specified operations.
Example Code Snippets
Printing Object Properties to the Console
let person = {
name: 'John',
age: 30,
city: 'New York'
};
for (let key in person) {
console.log(key + ': ' + person[key]);
}
In this example, a person
object is defined. The for...in
loop is used to print each property of the object to the console.
Printing Object Properties to HTML
<div id="output"></div>
<script>
let car = {
brand: 'Toyota',
model: 'Corolla',
year: 2020
};
let output = document.getElementById('output');
for (let key in car) {
output.innerHTML += '<p>' + key + ': ' + car[key] + '</p>';
}
</script>
In this example, a car
object is defined. The for...in
loop is used to print each property of the object into HTML.
Important Notes
- The
for...in
loop only returns the object’s own properties, not the inherited ones. - You can use the
hasOwnProperty()
method to ensure that the property belongs to the object itself. - The order of properties in the loop is not guaranteed, so the sequence of properties is not important.
The for...in
loop in JavaScript is a powerful tool for iterating over objects and processing their properties. When used correctly, it allows easy manipulation of object properties.