How to make object iterable

afozbek

Abdullah Furkan Özbek

Posted on August 17, 2021

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

💖 💪 🙅 🚩
afozbek
Abdullah Furkan Özbek

Posted on August 17, 2021

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related

How to make object iterable
iterable How to make object iterable

August 17, 2021