WalzoneInterview Prep
📞 Interviewing soon? Practice with a realistic AI mock phone interview — it calls you, then scores you. First 15 min FREE →

JavaScript · Advanced · question 43 of 100

How do you implement custom iterators using JavaScript’s iterator and generator functions?

📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

JavaScript’s iterator and generator functions allow developers to create custom iterators that can be used to iterate over collections of data in a flexible and efficient way. Here’s an example of how to implement a custom iterator using iterator and generator functions:

    const myIterable = {
        data: [1, 2, 3, 4, 5],
        [Symbol.iterator]: function*() {
            let currentIndex = 0;
            while (currentIndex < this.data.length) {
                yield this.data[currentIndex++];
            }
        }
    };
    
    for (let item of myIterable) {
        console.log(item);
    }

In this example, we define an object myIterable that contains an array of data and a custom iterator function that uses a generator function to yield each element of the array in turn. The Symbol.iterator property of the object is set to the generator function using the generator function syntax (function*).

To use the custom iterator, we can simply use a for...of loop to iterate over the elements of the object. The loop will automatically use the custom iterator defined on the object.

Custom iterators can be used to iterate over any collection of data in JavaScript, including arrays, sets, and maps. They are particularly useful when working with large or complex data sets where traditional iteration methods may be too slow or inflexible.

In summary, custom iterators can be implemented in JavaScript using the Symbol.iterator property and a generator function. By defining custom iterators, developers can create flexible and efficient ways to iterate over collections of data in their JavaScript code.

Reading is step one. Saying it out loud is the interview. Our AI interviewer calls your phone and runs a realistic JavaScript interview — then scores it.
📞 Practice JavaScript — free 15 min
📕 Buy this interview preparation book: 100 JavaScript questions & answers — PDF + EPUB for $5

All 100 JavaScript questions · All topics