The for...in statement loops through the properties (keys) of
an Object. It is designed specifically for objects, not arrays.
In each iteration, one property (key) of the object is assigned to the variable.
for (key in object) {
// code block to be executed
}
const person = { fname: "Mim", lname: "Akter", age: 22 };
let text = "";
for (let x in person) {
text += person[x] + " "; // Accessing the value using the key
}
// Result: Mim Akter 22
You can use for...in over an array, but it is generally avoided.
It iterates over the array indexes (0, 1, 2) instead of the values.
For arrays, a cleaner and more modern approach is forEach():
const numbers = [45, 4, 9, 16, 25];
numbers.forEach(function(value) {
console.log(value);
});
for...in is for iterating over Object
propertiesobject[key] to get the property
valuefor...in for Arrays where order is important