The for…in loop iterates over all enumerable properties of an object, including inherited ones. It goes through property names, not values. To get the value, you need to use square brackets with the property name.
The for…in loop is a way to go through all properties of an object. It’s very simple to use, but has features you need to know about.
The loop goes through names of all enumerable properties:
const user = { name: 'John', age: 25 };
for (let key in user) {
console.log(key); // Will output 'name', then 'age'
console.log(user[key]); // Will output 'John', then 25
}const obj = { a: 1, b: 2 };
// Will iterate a and bconst obj = {};
// Will iterate toString, hasOwnProperty and other inherited methodsconst user = {
name: 'John',
age: 25,
city: 'Moscow'
};
for (let prop in user) {
console.log(prop + ': ' + user[prop]);
}
// name: John
// age: 25
// city: Moscow// Numeric keys go first in ascending order
const obj = { 3: 'three', 1: 'one', 2: 'two', a: 'letter' };
// Order: 1, 2, 3, aconst obj = { name: 'John' };
// obj.toString is also iterated!
for (let key in obj) {
console.log(key); // name, toString, hasOwnProperty...
}const obj = { name: 'John' };
for (let key in obj) {
// Check that property belongs to object
if (obj.hasOwnProperty(key)) {
console.log(key + ': ' + obj[key]);
}
}const user = { name: 'John', age: 25 };
// Best way - iterate only own properties
for (let key in user) {
if (user.hasOwnProperty(key)) {
console.log(key, user[key]);
}
}// ❌ Iterating extra stuff
const obj = { name: 'John' };
for (let key in obj) {
console.log(obj[key]); // Will output name, toString, other methods
}
// ✅ Only own properties
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(obj[key]); // Only name
}
}// ❌ Don't rely on order (before ES6)
const obj = { b: 2, a: 1, c: 3 };
// Order may be different
// ✅ For order use arrays or MapThe for…in loop is convenient for simple property iteration, but always check that property belongs to the object itself using hasOwnProperty.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪