Home

JavaScript: Make an Iterable Class

Marko- Jan 19, 2022

In JavaScript, we can iterate an iterable object using the built-in for ... of syntax. We can make a class iterable by implementing the iterable protocol. To implement the protocol, the class must have a property with a @@iterator key which is available via constant Symbol.iterator

class Items { constructor(height, width) { this.list = [1, 2, 3, 4, 5]; } // the protocol interface should return an object with a next method [Symbol.iterator]() { // Use a new index for each iterator. This makes multiple // iterations over the iterable safe for non-trivial cases, // such as use of break or nested looping over the same iterable. let index = 0; return { next: () => { const value = this.list[index]; const done = index >= this.list.length - 1; index++; return { value, done } } } } }

Then we can iterate over this class like we did with a built-it iterable object (array, may, etc.)

const items = new Items(); for (const item of items) { console.log(item); }
Tags: blog-post