DEV Community

Mahdi Falamarzi
Mahdi Falamarzi

Posted on • Updated on

How to iterate through objects in javascript?

Iterables
It's a kind of new mechanism to iterate or traverse through data structures.
As you know Arrays, String, Maps and Sets or other similar collections are already iterable (it means we can use for of loop to iterate them) but objects are not.

when running the below code we had an error that
TypeError: obj is not iterable

Image description

How to create an iterator?
The "[Symbol.iterator]" method must be implemented which should return an iterator object that should have a next() method that returns the object.

How to create an iterator with generator function?
In this example, we implement "[Symbol.iterator]" with generator function!

Image description

Conclusion
Although you can iterate through an object with "for in" or "Object.entries", "Object.keys" and "Object.values" (convert to array and iterate on them) but in this article, we introduce a new way to iterate objects with "[Symbol.iterate]" and function generator.

Top comments (0)