How to Loop Through a JavaScript Object Tutorial

Learn every way to loop through JavaScript objects including for...in, Object.keys, Object.values, Object.entries, and forEach patterns for clean iteration.

JavaScriptbeginner
10 min read

JavaScript objects do not have a built-in .forEach() method like arrays do. That means you need different strategies to iterate over an object's keys and values. Whether you are building a settings panel, rendering form fields, or processing API responses, looping through objects is something you will do constantly.

This tutorial covers every practical approach to object iteration with real code examples, performance notes, and guidance on which method to pick for each situation.

Why Objects Need Special Iteration

Arrays are ordered collections with numeric indexes, so a standard for loop or .forEach() works naturally. Objects store data as key-value pairs without guaranteed numeric ordering. You need tools that understand property names rather than indexes.

javascriptjavascript
const user = {
  name: "Jordan",
  role: "Developer",
  level: 3,
  active: true
};
 
// This does NOT work - objects don't have .forEach
// user.forEach(...) // TypeError: user.forEach is not a function
 
// You need one of the methods below

JavaScript gives you several ways to handle this. Each has trade-offs around readability, performance, and what exactly gets iterated.

The for...in Loop

The for...in loop is the oldest and most direct way to iterate over object properties. It walks through every enumerable property, including inherited ones from the prototype chain.

javascriptjavascript
const product = {
  name: "Mechanical Keyboard",
  price: 89.99,
  inStock: true,
  category: "Electronics"
};
 
for (const key in product) {
  console.log(`${key}: ${product[key]}`);
}
// name: Mechanical Keyboard
// price: 89.99
// inStock: true
// category: Electronics

Filtering Inherited Properties

The for...in loop also picks up properties from the prototype chain. In most real code you want only the object's own properties. Use hasOwnProperty() or Object.hasOwn() to filter:

javascriptjavascript
function Vehicle(type) {
  this.type = type;
}
Vehicle.prototype.wheels = 4;
 
const car = new Vehicle("sedan");
car.color = "blue";
 
// Without filter - includes inherited 'wheels'
for (const key in car) {
  console.log(key); // type, color, wheels
}
 
// With hasOwnProperty filter
for (const key in car) {
  if (Object.hasOwn(car, key)) {
    console.log(key); // type, color (no 'wheels')
  }
}

Object.hasOwn() is the modern replacement for hasOwnProperty() and works correctly even when an object has overridden hasOwnProperty as its own property.

Using Object.keys() with forEach

Object.keys() returns an array of the object's own enumerable property names. You can then use any array method to iterate:

javascriptjavascript
const config = {
  theme: "dark",
  language: "en",
  fontSize: 16,
  autoSave: true
};
 
Object.keys(config).forEach(key => {
  console.log(`${key} = ${config[key]}`);
});
// theme = dark
// language = en
// fontSize = 16
// autoSave = true

This approach automatically excludes inherited properties, so you do not need the hasOwnProperty check. It also gives you access to the full array method toolkit: .filter(), .map(), .reduce(), and more.

javascriptjavascript
// Find all string-type settings
const stringSettings = Object.keys(config)
  .filter(key => typeof config[key] === "string");
 
console.log(stringSettings); // ["theme", "language"]

Using Object.values() for Values Only

When you only care about the values and not the keys, Object.values() is the cleanest choice:

javascriptjavascript
const scores = {
  math: 92,
  english: 88,
  science: 95,
  history: 78
};
 
const allScores = Object.values(scores);
console.log(allScores); // [92, 88, 95, 78]
 
// Calculate the average
const average = allScores.reduce((sum, val) => sum + val, 0) / allScores.length;
console.log(`Average: ${average}`); // Average: 88.25

This is particularly useful for aggregation, validation, or when you need to pass values to a function that expects an array.

Using Object.entries() for Key-Value Pairs

Object.entries() returns an array of [key, value] pairs. Combined with destructuring, it produces the most readable iteration code:

javascriptjavascript
const employee = {
  name: "Maya",
  department: "Engineering",
  salary: 95000,
  startYear: 2022
};
 
for (const [key, value] of Object.entries(employee)) {
  console.log(`${key}: ${value}`);
}
// name: Maya
// department: Engineering
// salary: 95000
// startYear: 2022

Transforming Objects During Iteration

Object.entries() combined with Object.fromEntries() lets you transform objects in a functional pipeline:

javascriptjavascript
const prices = {
  laptop: 999,
  phone: 699,
  tablet: 449,
  headphones: 199
};
 
// Apply a 10% discount to all items
const discounted = Object.fromEntries(
  Object.entries(prices).map(([item, price]) => [item, price * 0.9])
);
 
console.log(discounted);
// { laptop: 899.1, phone: 629.1, tablet: 404.1, headphones: 179.1 }

for...of with Object.entries()

The for...of loop works with any iterable. Since Object.entries() returns an array, you can combine them for clean, breakable iteration:

javascriptjavascript
const inventory = {
  apples: 50,
  bananas: 0,
  oranges: 25,
  grapes: 0,
  pears: 15
};
 
// Find the first out-of-stock item
for (const [fruit, count] of Object.entries(inventory)) {
  if (count === 0) {
    console.log(`${fruit} is out of stock!`);
    break; // Stop after finding the first one
  }
}
// bananas is out of stock!

Unlike .forEach(), the for...of loop supports break and continue, making it the better choice when you need early termination.

Method Comparison Table

MethodReturnsInherited PropsBreak/ContinueBest For
for...inKeys (one at a time)Yes (needs filter)YesSimple iteration, legacy code
Object.keys().forEach()Key arrayNoNoKey-only iteration with array methods
Object.values().forEach()Value arrayNoNoValue-only aggregation
Object.entries().forEach()[key, value] arrayNoNoKey-value pairs with array chaining
for...of + Object.entries()[key, value] pairsNoYesEarly exit, conditional logic

Performance Comparison

For small objects (under 100 properties), all methods perform similarly. For larger objects, here is a general ranking:

MethodRelative SpeedNotes
for...in + hasOwnFastestNo intermediate array created
for...of + Object.keys()FastSingle array allocation
Object.keys().forEach()FastSingle array, callback overhead
Object.entries().forEach()SlowerCreates array of arrays
Object.entries() + .map() + fromEntries()SlowestMultiple array allocations

In practice, readability matters more than micro-optimization for most applications. Choose Object.entries() for clarity unless profiling shows it as a bottleneck.

Real-World Example: Settings Panel Builder

Here is a practical example that builds a settings form from a configuration object:

javascriptjavascript
const settings = {
  darkMode: { value: true, type: "boolean", label: "Dark Mode" },
  fontSize: { value: 16, type: "number", label: "Font Size" },
  language: { value: "en", type: "select", label: "Language" },
  notifications: { value: false, type: "boolean", label: "Notifications" },
  autoSave: { value: true, type: "boolean", label: "Auto Save" }
};
 
function buildSettingsHTML(settingsObj) {
  const rows = [];
 
  for (const [key, config] of Object.entries(settingsObj)) {
    let inputHTML;
 
    if (config.type === "boolean") {
      const checked = config.value ? "checked" : "";
      inputHTML = `<input type="checkbox" name="${key}" ${checked}>`;
    } else if (config.type === "number") {
      inputHTML = `<input type="number" name="${key}" value="${config.value}">`;
    } else {
      inputHTML = `<input type="text" name="${key}" value="${config.value}">`;
    }
 
    rows.push(`<label>${config.label}: ${inputHTML}</label>`);
  }
 
  return `<form>${rows.join("\n")}</form>`;
}
 
console.log(buildSettingsHTML(settings));

This pattern is common in admin dashboards where configuration objects drive the UI rendering.

Common Mistakes to Avoid

Trying Array Methods on Objects Directly

Objects do not have .forEach(), .map(), or .filter(). Always convert first:

javascriptjavascript
const data = { a: 1, b: 2, c: 3 };
 
// Wrong - TypeError
// data.forEach(...)
 
// Correct - convert to entries first
Object.entries(data).forEach(([key, val]) => {
  console.log(key, val);
});

Forgetting for...in Includes Inherited Properties

javascriptjavascript
// This can cause unexpected results with prototype pollution
for (const key in someObject) {
  // Always guard with hasOwn in production code
  if (Object.hasOwn(someObject, key)) {
    processProperty(key, someObject[key]);
  }
}

Modifying an Object While Iterating

Adding or deleting properties during iteration produces unpredictable behavior:

javascriptjavascript
const items = { a: 1, b: 2, c: 3 };
 
// Dangerous - modifying during iteration
for (const key in items) {
  if (items[key] < 2) {
    delete items[key]; // Unpredictable!
  }
}
 
// Safe - collect keys first, then modify
const keysToDelete = Object.keys(items).filter(k => items[k] < 2);
keysToDelete.forEach(k => delete items[k]);

Best Practices

  1. Default to Object.entries() for most iteration needs. It gives you both keys and values with clean destructuring.
  2. Use for...of instead of .forEach() when you might need break or continue.
  3. Avoid for...in without hasOwn in production code unless you are certain about the prototype chain.
  4. Use Object.keys() for key-only operations like counting properties or checking for specific keys.
  5. Use Object.values() for aggregation tasks like summing, averaging, or finding min/max.
Rune AI

Rune AI

Key Insights

  • Object.entries() is the most versatile: it gives you both keys and values with clean destructuring syntax
  • for...in requires hasOwn guards: always filter inherited properties in production code to avoid prototype chain surprises
  • Use for...of when you need break/continue: unlike .forEach(), the for...of loop supports early termination
  • Object.values() excels at aggregation: use it for summing, averaging, or any operation that only needs values
  • Performance rarely matters here: choose readability over micro-optimization unless profiling identifies object iteration as a bottleneck
RunePowered by Rune AI

Frequently Asked Questions

Can I use a regular for loop to iterate over an object?

No. A standard `for` loop requires numeric indexes, which objects do not have. You need `for...in`, `for...of` with `Object.entries()`, or an Object static method like `Object.keys()` to iterate over object properties. Converting to an array with [`Object.entries()`](/tutorials/programming-languages/javascript/js-object-keys-values-and-entries-full-guide) lets you use any array-based iteration pattern.

What is the difference between for...in and for...of for objects?

`for...in` iterates over enumerable property names (including inherited ones) and works directly on objects. `for...of` iterates over iterable values and does NOT work on plain objects directly. You need to wrap the object with `Object.entries()`, `Object.keys()`, or `Object.values()` first. The `for...of` approach is generally preferred because it excludes inherited properties automatically.

Does JavaScript guarantee the order of object properties?

Yes, since ES2015. Integer-like keys come first in ascending numeric order, then string keys in insertion order, then Symbol keys in insertion order. For most practical cases with string keys, properties iterate in the order you added them. If order matters critically, consider using a [Map](/tutorials/programming-languages/javascript/js-object-keys-values-and-entries-full-guide) instead of a plain object.

How do I loop through nested objects?

Use recursion or a stack-based approach. Call your iteration function again when a value is itself an object. For example, `Object.entries(obj).forEach(([key, val]) => { if (typeof val === 'object' && val !== null) { iterateNested(val); } })`. Be careful with circular references, which would cause infinite recursion.

Which iteration method is fastest for large objects?

`for...in` with `Object.hasOwn()` is generally the fastest because it avoids creating intermediate arrays. However, the difference is negligible for objects with fewer than 1,000 properties. For most applications, choose the method that produces the most readable code rather than optimizing for speed.

Conclusion

Looping through JavaScript objects requires converting them to iterable formats since objects lack built-in iteration methods like arrays. The five main approaches (for...in, Object.keys(), Object.values(), Object.entries(), and for...of combinations) each serve different use cases, from simple key access to complex transformations.