Are Objects Iterable in JavaScript?
Last Updated :
28 Nov, 2024
In JavaScript, plain objects are not iterable by default, meaning you cannot directly use constructs like for...of loops or the spread operator (...) with them. However, arrays (a), strings, maps, and sets are inherently iterable.
Understanding Iterables in JavaScript
An iterable is an object that implements the @@iterator method, accessible via the Symbol.iterator property. This method returns an iterator object that defines a sequence and potentially a return value upon its completion. Iterables can be used with for...of loops, the spread operator etc.
JavaScript
const a = [1, 2, 3];
for (const item of a) {
console.log(item);
}
Plain Objects and Iterability
Plain objects do not have a default Symbol.iterator property, making them non-iterable by default. Attempting to use a for...of loop or the spread operator with a plain object will result in a TypeError.
JavaScript
const obj = { a: 1, b: 2, c: 3 };
for (const item of obj) {
console.log(item);
}
Output
TypeError: obj is not iterable
Iterating Over Plain Objects
While plain objects are not iterable, you can iterate over their properties using methods like Object.keys(), Object.values(), and Object.entries().
Using Object.keys()
JavaScript
const obj = { a: 1, b: 2, c: 3 };
Object.keys(obj).forEach(key => {
console.log(`${key}: ${obj[key]}`);
});
Using Object.values()
JavaScript
const obj = { a: 1, b: 2, c: 3 };
Object.values(obj).forEach(value => {
console.log(value);
});
Using Object.entries()
JavaScript
const obj = { a: 1, b: 2, c: 3 };
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key}: ${value}`);
});
Making Plain Objects Iterable
To make a plain object iterable, you can define a Symbol.iterator method that returns an iterator object. This allows the object to be used with for...of loops and other iterable contexts.
JavaScript
const obj = { a: 1, b: 2, c: 3 };
obj[Symbol.iterator] = function* () {
for (const key of Object.keys(this)) {
yield [key, this[key]];
}
};
for (const [key, value] of obj) {
console.log(`${key}: ${value}`);
}
Explanation
- The Symbol.iterator method is defined as a generator function.
- It iterates over the object's own keys using Object.keys(this).
- For each key, it yields a [key, value] pair.
- The for...of loop can now iterate over these [key, value] pairs.
Conclusion
Plain objects in JavaScript are not iterable by default because they lack the Symbol.iterator method. However, you can iterate over their properties using methods like Object.keys(), Object.values(), and Object.entries(). Additionally, by defining a custom Symbol.iterator method, you can make a plain object iterable.