The for…in loop iterates over the enumerable properties of an object.It is commonly used for objects, but can also be used with arrays (with caution).

1.Syntax

for (variable in object) {
// code to execute
}
  • variable → receives property key (string) on each iteration
  • object → object whose enumerable properties will be iterated

2.Basic Example (Object)

const user = {
name: "Zaman",
age: 25,
city: "Dhaka"
};
for (let key in user) {
console.log(key, user[key]);
}

Output:

name Zaman
age 25
city Dhaka

✔ Iterates over keys
✔ Access values using user[key]

3.Iterating Over Arrays (Not Recommended)

const arr = [10, 20, 30]; 
for (let index in arr) { 
 console.log(index, arr[index]); 
}

Output:

0 10
1 20
2 30

❌ Issue: for…in iterates all enumerable properties, including inherited ones
✅ Better for arrays: for…of or .forEach()

4.Iterating Over Object Prototype Properties

function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log("Hello");
};

const p = new Person("Zaman");

for (let key in p) {
console.log(key);
}

Output:

name
greet

for…in iterates inherited enumerable properties
✔ Use hasOwnProperty to filter

for (let key in p) {
if (p.hasOwnProperty(key)) {
console.log(key); // only "name"
}
}

5.Using for…in With Objects (Recommended)

const product = {
id: 101,
name: "Laptop",
price: 500
};
for (const key in product) {
console.log(`${key} : ${product[key]}`);
}

Output:

id : 101
name : Laptop
price : 500

Categorized in:

Javascript,