How to iterate all object properties with for...in loop?

👨‍💻 Frontend Developer 🟠 May come up 🎚️ Easy
#JavaScript #Objects #JS Basics

Brief Answer

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.


Full Answer

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.

How for…in Works

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
}

What for…in Iterates

Own Properties

const obj = { a: 1, b: 2 };
// Will iterate a and b

Inherited Properties

const obj = {};
// Will iterate toString, hasOwnProperty and other inherited methods

Simple Examples

Iterating Simple Object

const user = { 
  name: 'John', 
  age: 25, 
  city: 'Moscow' 
};
 
for (let prop in user) {
  console.log(prop + ': ' + user[prop]);
}
// name: John
// age: 25
// city: Moscow

Important Features

1. Iteration Order

// Numeric keys go first in ascending order
const obj = { 3: 'three', 1: 'one', 2: 'two', a: 'letter' };
// Order: 1, 2, 3, a

2. Inherited Properties

const obj = { name: 'John' };
// obj.toString is also iterated!
 
for (let key in obj) {
  console.log(key); // name, toString, hasOwnProperty...
}

How to Avoid Problems

Checking Own Properties

const obj = { name: 'John' };
 
for (let key in obj) {
  // Check that property belongs to object
  if (obj.hasOwnProperty(key)) {
    console.log(key + ': ' + obj[key]);
  }
}

Only Own Properties

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]);
  }
}

Common Mistakes

1. Iterating Inherited Properties

// ❌ 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
  }
}

2. Expecting Property Order

// ❌ Don't rely on order (before ES6)
const obj = { b: 2, a: 1, c: 3 };
// Order may be different
 
// ✅ For order use arrays or Map

Simple Rules

  1. for…in — for iterating property names of object
  2. user[key] — to get property value
  3. hasOwnProperty — to filter inherited properties
  4. Order — numeric keys go first
  5. Careful — iterates all enumerable properties

The 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 💪