1. Mark an object iterable
To mark an object iterable, you need to add a Symbol.iterator property to it:
The Symbol.iterator part looks really odd if you don't know what Symbol is all about. One way to think about it is to see it as metadata that describes the hidden behaviors of an object. When an object is marked with the iterator symbol, it means you can loop through it like an array.
2. Return an iterator object
The code snippet above returns an iterator object. An iterator object needs to have a next method which is a function that returns an iterator result object:
3. Return an iterator result object
Finally, I mean finally we can return some real values rather than wrappers that conforms to the iterable and iterator protocal.The iterator result object has to have two properties, one named value and the other named done.
As long as an object has the three traits explained above, it is iterable and can be used in a for...of loop or being spreaded [...myObj].