Course contentsShow
← JavaScript
Lesson 355 of 2,72310. LoopsFree lesson

For...in with Objects

Iterate over an object's own enumerable properties using for...in.

For...in with Objects

In this lesson, you'll learn how to iterate over an object's own enumerable properties using a for...in loop.

Why For...in Exists

Objects in JavaScript are collections of key-value pairs. Unlike arrays, which have numeric indices, objects have property names (keys). The for...in loop was designed specifically to walk through these property names, letting you access each key (and its value) one at a time.

Basic Syntax

const person = {
  name: "Alice",
  age: 30,
  city: "Boston"
};

for (let key in person) {
  console.log(key); // "name", "age", "city"
}

On each iteration, the loop variable (key here) receives the property name as a string. You can then use bracket notation to access the value:

for (let key in person) {
  console.log(key + ": " + person[key]);
}
// Output:
// name: Alice
// age: 30
// city: Boston

What Gets Iterated

for...in loops over an object's own enumerable properties—basically, the properties you directly assigned to that object. Think of it like checking every labeled drawer in a desk to see what's inside.

A Quick Note

Unlike for...of (which iterates over values), for...in gives you the keys. You must use object[key] to retrieve the corresponding value.

Example in Action

const scores = {
  math: 95,
  english: 88,
  science: 92
};

for (let subject in scores) {
  console.log(subject + " score is " + scores[subject]);
}

Key Takeaway: Use for...in to iterate over an object's property names (keys), then access values with bracket notation.