Furkan's Notes

Furkan's Notes

How to make object iterable

How to make object iterable

Listen to this article

In order to be iterable, an object must implement the @@iterator method. This means that the object (or one of the objects up its prototype chain) must have a property with a Symbol.iterator key.

If you want to create your own iterable object here is how you can do it.

const iterable = {
    *[Symbol.iterator]() {
        yield 1;
        yield 2;
        yield 3;
    }
}

for (let value of iterable) {
    console.log(value);
}
// 1
// 2
// 3
 
Share this