Iterating Non-Iterable Objects
You'll learn how to work around plain objects' lack of built-in iteration support in JavaScript.
The Problem
Plain JavaScript objects ({}) are not iterable by default. They don't have a Symbol.iterator method, so you can't use them directly with for...of loops or spread syntax. Try it and you'll get an error: TypeError: object is not iterable.
const person = { name: "Alice", age: 30 };
// for (const item of person) { } // ❌ TypeError!
Built-In Solutions
JavaScript provides three static methods on Object to extract iterable arrays from plain objects:
Object.keys(obj)— returns an array of property namesObject.values(obj)— returns an array of property valuesObject.entries(obj)— returns an array of[key, value]pairs
const person = { name: "Alice", age: 30 };
for (const key of Object.keys(person)) {
console.log(key); // "name", "age"
}
for (const [key, value] of Object.entries(person)) {
console.log(`${key}: ${value}`); // "name: Alice", "age: 30"
}
Custom Iterator Approach
Alternatively, you can add Symbol.iterator directly to make an object iterable:
const person = {
name: "Alice",
age: 30,
[Symbol.iterator]() {
const keys = Object.keys(this);
let index = 0;
return {
next: () => {
if (index < keys.length) {
const key = keys[index++];
return { value: [key, this[key]], done: false };
}
return { done: true };
}
};
}
};
for (const [key, value] of person) {
console.log(`${key}: ${value}`); // Now it works!
}
Key Takeaway: Plain objects aren't iterable, but you can use Object.keys(), Object.values(), or Object.entries() to convert them into iterable arrays, or add a custom Symbol.iterator method to make them directly iterable.