![]() |
VOOZH | about |
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.
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.
1 2 3
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.
Output
TypeError: obj is not iterableWhile plain objects are not iterable, you can iterate over their properties using methods like Object.keys(), Object.values(), and Object.entries().
a: 1 b: 2 c: 3
1 2 3
a: 1 b: 2 c: 3
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.
a: 1 b: 2 c: 3
Explanation
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.