DEV Community

Cover image for How to make object iterable
Abdullah Furkan Özbek
Abdullah Furkan Özbek

Posted on

How to make object iterable

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
Enter fullscreen mode Exit fullscreen mode

Links

Top comments (0)