Course contentsShow
← JavaScript
Lesson 639 of 2,72315. ObjectsFree lesson

For...in Loop for Enumerable Properties

Use for...in to iterate over an object's own enumerable properties and inherited ones.

For...in Loop for Enumerable Properties

What you'll learn: How to use the for...in loop to iterate through an object's enumerable properties, including its own and inherited ones.

The Core Idea

While arrays use for...of or traditional for loops, objects need a different approach for iteration. The for...in loop walks through all enumerable properties of an object, giving you access to each property name (key) one at a time.

Think of it like reading a directory: the for...in loop opens your object's "folder" and reads out each visible file name, including files inherited from parent folders.

How It Works

const person = {
  name: 'Alice',
  age: 30,
  job: 'Developer'
};

for (let key in person) {
  console.log(key); // Logs: 'name', 'age', 'job'
  console.log(person[key]); // Logs the values
}

The loop variable (key here) holds the property name as a string on each iteration. You access the value using bracket notation: person[key].

Inherited Properties Too

Here's where for...in differs from Object.keys(): it includes inherited enumerable properties from the prototype chain, not just the object's own properties:

const child = Object.create(person); // child inherits from person
child.school = 'Code Academy';

for (let key in child) {
  console.log(key); // Logs: 'school', 'name', 'age', 'job'
}

To check only own properties, combine with hasOwnProperty():

for (let key in child) {
  if (child.hasOwnProperty(key)) {
    console.log(key); // Only logs: 'school'
  }
}

Key Takeaway: The for...in loop iterates over all enumerable properties of an object, including those inherited from its prototype chain—use it when you need comprehensive property access, and filter with hasOwnProperty() when you want only the object's own properties.