The for...in
loop is a JavaScript loop used to iterate over the properties of an object. It works by looping over all the enumerable properties of an object, including any properties inherited from its prototype chain. The syntax for the for...in
loop is as follows:
for (variable in object) {
// code to be executed
}
Here, variable
is a variable that represents each property name in the object as the loop iterates, and object
is the object being iterated over. Inside the loop, you can use the variable
to access the value of each property.
Here’s an example that demonstrates the use of the for...in
loop:
const person = {
name: 'John',
age: 30,
gender: 'male'
};
for (let property in person) {
console.log(property + ': ' + person[property]);
}
In this example, the for...in
loop is used to iterate over the properties of the person
object. The loop iterates three times, with property
taking on the values 'name'
, 'age'
, and 'gender'
in each iteration. Inside the loop, the property name and value are printed to the console using string concatenation.