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.
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.
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 belowJavaScript 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.
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: ElectronicsFiltering 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:
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:
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 = trueThis 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.
// 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:
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.25This 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:
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: 2022Transforming Objects During Iteration
Object.entries() combined with Object.fromEntries() lets you transform objects in a functional pipeline:
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:
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
| Method | Returns | Inherited Props | Break/Continue | Best For |
|---|---|---|---|---|
for...in | Keys (one at a time) | Yes (needs filter) | Yes | Simple iteration, legacy code |
Object.keys().forEach() | Key array | No | No | Key-only iteration with array methods |
Object.values().forEach() | Value array | No | No | Value-only aggregation |
Object.entries().forEach() | [key, value] array | No | No | Key-value pairs with array chaining |
for...of + Object.entries() | [key, value] pairs | No | Yes | Early exit, conditional logic |
Performance Comparison
For small objects (under 100 properties), all methods perform similarly. For larger objects, here is a general ranking:
| Method | Relative Speed | Notes |
|---|---|---|
for...in + hasOwn | Fastest | No intermediate array created |
for...of + Object.keys() | Fast | Single array allocation |
Object.keys().forEach() | Fast | Single array, callback overhead |
Object.entries().forEach() | Slower | Creates array of arrays |
Object.entries() + .map() + fromEntries() | Slowest | Multiple 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:
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:
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
// 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:
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
- Default to
Object.entries()for most iteration needs. It gives you both keys and values with clean destructuring. - Use
for...ofinstead of.forEach()when you might needbreakorcontinue. - Avoid
for...inwithouthasOwnin production code unless you are certain about the prototype chain. - Use
Object.keys()for key-only operations like counting properties or checking for specific keys. - Use
Object.values()for aggregation tasks like summing, averaging, or finding min/max.
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(), thefor...ofloop 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
Frequently Asked Questions
Can I use a regular for loop to iterate over an object?
What is the difference between for...in and for...of for objects?
Does JavaScript guarantee the order of object properties?
How do I loop through nested objects?
Which iteration method is fastest for large objects?
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.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.