Question

How to Iterate Through Object Properties in JavaScript

javascriptloopsobject

Question

In JavaScript, consider this object and loop:

var obj = {
  name: "Simon",
  age: "20",
  clothing: {
    style: "simple",
    hipster: false
  }
};

for (var propt in obj) {
  console.log(propt + ': ' + obj[propt]);
}

How does the variable propt represent the properties of the object? It is not a built-in method or property. Why does it receive each property name from the object during the loop?

Short Answer

By the end of this page, you will understand how the JavaScript for...in loop works, why the loop variable can have any name, and how it gets assigned each enumerable property name of an object one at a time. You will also learn safer modern alternatives such as Object.keys(), Object.values(), and Object.entries().

Concept

In JavaScript, for...in is a special loop used to iterate over the property names of an object.

When you write:

for (var propt in obj) {
  console.log(propt);
}

JavaScript reads this as:

  • Look at the object obj
  • Find its enumerable property names
  • For each property name, assign that name to the variable propt
  • Run the loop body

The important point is that propt is just a variable name you chose. It is not built in. You could call it key, property, x, or anything valid:

for (var key in obj) {
  console.log(key);
}

This works the same way.

In your example, the loop visits these top-level properties:

  • name
  • age
  • clothing

So on each iteration:

  • propt becomes "name"
  • then "age"
  • then "clothing"

Then obj[propt] uses bracket notation to access the corresponding value.

Why this matters:

  • Objects are one of the main ways JavaScript stores structured data.
  • Many real programs need to inspect object keys dynamically.
  • You often do this when validating input, building logs, formatting API responses, or transforming data.

One more important detail: for...in loops over enumerable properties, including inherited ones unless you filter them. That is why developers often prefer Object.keys(obj) for predictable iteration over an object's own properties.

Mental Model

Think of an object like a labeled storage cabinet:

  • name is one drawer label
  • age is another drawer label
  • clothing is another drawer label

A for...in loop is like saying:

"Go through each drawer label in this cabinet, one by one, and write the current label on a sticky note."

That sticky note is your loop variable.

So propt is not special. It is just the sticky note name you chose. JavaScript keeps updating it with the next property label during the loop.

Take Quiz

Syntax and Examples

Basic syntax

for (var key in object) {
  // use key
}
  • key is a normal variable
  • object is the object being inspected
  • On each loop, key contains the next property name as a string

Example: logging keys and values

var user = {
  name: "Simon",
  age: 20,
  active: true
};

for (var key in user) {
  console.log(key);         // property name
  console.log(user[key]);   // property value
}

Possible output:

name
Simon
age
20
active
true

Why bracket notation is used

This works:

console.log(user[key]);

This does not do what you want:

console.log(user.key);

user.key looks for a property literally named key, while user[key] uses the value stored in the variable key.

Nested object example

var obj = {
  name: "Simon",
  age: 20,
  clothing: {
    style: "simple",
    hipster: false
  }
};

for (var key in obj) {
  console.log(key + ':', obj[key]);
}

Output will include:

name: Simon
age: 20
clothing: { style: 'simple', hipster: false }

Notice that for...in only loops over the top-level properties of obj. It does not automatically go inside clothing.

Step by Step Execution

Consider this code:

var obj = {
  name: "Simon",
  age: 20,
  clothing: {
    style: "simple",
    hipster: false
  }
};

for (var propt in obj) {
  console.log(propt + ': ' + obj[propt]);
}

Step by step:

  1. JavaScript creates the object obj with three properties:

    • name
    • age
    • clothing
  2. The loop starts:

    for (var propt in obj)
    

    JavaScript prepares to iterate through the enumerable property names of obj.

  3. First iteration:

    • propt is assigned "name"
    • obj[propt] becomes obj["name"]
    • Result: "Simon"
    • Output:
    name: Simon
    
  4. Second iteration:

    • propt is assigned "age"
    • obj[propt] becomes obj["age"]
    • Result: 20
    • Output:
    age: 20
    
  5. Third iteration:

    • propt is assigned "clothing"
    • obj[propt] becomes obj["clothing"]
    • Result: the nested object
    • Output is the object itself
  6. No more enumerable properties remain, so the loop ends.

A shorter trace table:

Iterationpropt valueobj[propt] value
1"name""Simon"
2"age"20
3"clothing"{ style: "simple", hipster: false }

Real World Use Cases

for...in and object key iteration are useful when property names are not known in advance.

Common situations

  • Form validation: loop through submitted fields and check for empty values
  • Configuration objects: inspect settings and apply defaults
  • API response formatting: transform object fields into display text
  • Debugging: log all properties in an object
  • Data cleanup: remove or normalize invalid values

Example: validating form data

var formData = {
  username: "simon",
  email: "",
  password: "secret123"
};

for (var key in formData) {
  if (formData[key] === "") {
    console.log(key + " is required");
  }
}

Example: printing config values

var config = {
  theme: "dark",
  notifications: true,
  language: "en"
};

for (var key in config) {
  console.log(key + " = " + config[key]);
}
Take Quiz

Real Codebase Usage

In real projects, developers often iterate over object properties to process dynamic data. However, they usually do it carefully.

Common patterns

1. Filtering own properties

Because for...in can include inherited enumerable properties, developers often guard against that:

for (var key in obj) {
  if (Object.hasOwn(obj, key)) {
    console.log(key, obj[key]);
  }
}

2. Using Object.keys() for safer iteration

Object.keys(obj).forEach(function (key) {
  console.log(key, obj[key]);
});

This only returns the object's own enumerable property names.

3. Using Object.entries() when both key and value are needed

Object.entries(obj).forEach(function ([key, value]) {
  console.log(key, value);
});

4. Validation and early checks

function validateSettings(settings) {
  for (var key in settings) {
    if (!Object.hasOwn(settings, key)) continue;

    if (settings[key] == null) {
      return key + " cannot be null";
    }
  }

  return "OK";
}

Practical advice

  • Use for...in when you specifically want property names from an object
  • Prefer Object.keys() or Object.entries() in many modern codebases for clarity
  • Be careful with inherited properties when using for...in

Common Mistakes

1. Thinking the loop variable is built in

Wrong idea:

  • propt has special meaning

Reality:

  • It is just a variable name you chose

These are all valid:

for (var propt in obj) {}
for (var key in obj) {}
for (var propertyName in obj) {}

2. Using dot notation with the variable name

Broken code:

for (var key in obj) {
  console.log(obj.key);
}

Why it is wrong:

  • obj.key means a property literally called key
  • It does not mean "use the value inside the variable key"

Correct code:

for (var key in obj) {
  console.log(obj[key]);
}

3. Expecting nested objects to be iterated automatically

Broken expectation:

var obj = {
  user: {
    name: "Simon"
  }
};

for (var key in obj) {
  console.log(key, obj[key]);
}

This only gives user, not name.

If you want nested properties, you need another loop or recursion.

4. Forgetting inherited properties

Example:

var parent = { inheritedProp: "hello" };
var child = Object.create(parent);
child.ownProp = "world";

for (var key in child) {
  console.log(key);
}

This may print both:

  • ownProp
  • inheritedProp

Safer version:

for (var key in child) {
  if (Object.hasOwn(child, key)) {
    console.log(key);
  }
}

5. Using for...in on arrays

Possible but not recommended:

var arr = ["a", "b", "c"];

for (var index in arr) {
  console.log(index, arr[index]);
}

Better:

for (var i = 0; i < arr.length; i++) {
  console.log(i, arr[i]);
}

Or:

arr.forEach(function (value, index) {
  console.log(index, value);
});

Comparisons

for...in vs other ways to iterate objects

ApproachWhat it iteratesBest useNotes
for...inEnumerable property namesQuick object key iterationCan include inherited properties
Object.keys(obj)Own enumerable property namesSafe key iterationReturns an array of keys
Object.values(obj)Own enumerable valuesWhen only values matterNo keys returned
Object.entries(obj)Own enumerable key-value pairsWhen you need both key and valueVery readable

Example comparison

var user = {
  name: "Simon",
  age: 20
};

for...in

for (var key in user) {
  if (Object.hasOwn(user, key)) {
    console.log(key, user[key]);
  }
}

Object.keys()

Object.keys(user).forEach(function (key) {
  console.log(key, user[key]);
});

Object.entries()

Object.entries(user).forEach(function ([key, value]) {
  console.log(key, value);
});

for...in vs for...of

LoopUsed forWorks directly on plain objects?
for...inProperty namesYes
for...ofIterable valuesNo, not on plain objects

Example:

for (var key in user) {
  console.log(key);
}
for (var value of [1, 2, 3]) {
  console.log(value);
}
Take Quiz

Cheat Sheet

Quick reference

for...in syntax

for (var key in obj) {
  console.log(key, obj[key]);
}

Key facts

  • The loop variable can have any valid name
  • It stores the current property name as a string
  • Use bracket notation: obj[key]
  • for...in iterates enumerable properties
  • It may include inherited properties

Safer pattern

for (var key in obj) {
  if (Object.hasOwn(obj, key)) {
    console.log(key, obj[key]);
  }
}

Modern alternatives

Object.keys(obj)
Object.values(obj)
Object.entries(obj)

Common pitfall

Wrong:

obj.key

Right:

obj[key]

Nested objects

for...in does not automatically recurse into nested objects.

Avoid for arrays

Prefer:

array.forEach(...)
for (var i = 0; i < array.length; i++) {}
for (var value of array) {}

FAQ

Why can I name the loop variable anything in for...in?

Because it is just a normal variable. JavaScript assigns each property name to that variable during the loop.

Does for...in return values or keys?

It returns property names, also called keys. You then use obj[key] to get the value.

Why do I need obj[key] instead of obj.key?

obj[key] uses the variable's current value. obj.key looks for a property literally named key.

Does for...in work on nested objects automatically?

No. It only iterates the current object's top-level enumerable properties.

Is for...in safe for all objects?

It works, but it can include inherited properties. Use Object.hasOwn() or prefer Object.keys() when you only want the object's own keys.

Should I use for...in for arrays?

Usually no. Arrays are better handled with for, forEach, or for...of.

What does enumerable mean in JavaScript?

It means a property is visible during property enumeration, such as in a for...in loop.

Take Quiz

Mini Project

Description

Create a small utility that prints a user profile object in a readable way. This project helps you practice iterating through object properties, reading keys and values dynamically, and skipping nested objects when needed.

Goal

Build a function that loops through an object and prints each top-level property name with its value.

Requirements

[ "Create an object with at least four properties", "Use a for...in loop to iterate through the object", "Print each property name and its value", "If a value is an object, print a placeholder message instead of the full nested object" ]

Take Quiz

Keep learning

Related questions

View more