JavaScript for in
In JavaScript, you can cycle through an object's attributes by using the for...in the loop iteration type.
The basic syntax is as follows:
for (variable in object) { // code to be executed }
In this syntax, the variable is a variable that will hold the property name for each iteration, and the object is the object you want to iterate over.
This is an example:
let person = { firstName: "Olise", lastName: "Eke", age: 30 };
for (let property in person) { console.log(property + ": " + person[property]); }
In this example, you will create an object called a person with three properties: firstName, lastName, and age. you will then use a for...in the loop
to iterate over the properties of the person object and log their names and values to the console.
The output of this code will be:
firstName: Olise lastName: Eke age: 30
Example:
for (let property in person) { if (person.hasOwnProperty(property))
{ console.log(property + ": " + person[property]); } }
This will only log the object's properties to the console, excluding any inherited properties.
Last updated