DEV Community

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

Posted on

2 1

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)

This post blew up on DEV in 2020:

js visualized

🚀⚙️ JavaScript Visualized: the JavaScript Engine

As JavaScript devs, we usually don't have to deal with compilers ourselves. However, it's definitely good to know the basics of the JavaScript engine and see how it handles our human-friendly JS code, and turns it into something machines understand! 🥳

Happy coding!