AI solution for Interview Question on BFE.dev
161. explain iterators and generators
Iterators and generators are two features introduced in ES6 (also known as ECMAScript 2015) that allow us to iterate through data structures like arrays and objects.
An iterator is an object that provides a sequence of values, one at a time. It has a next()
method, and each time the method is called, it will return an object with two properties: value
and done
. The value
property contains the next value in the sequence, and the done
property is a Boolean that indicates whether we have reached the end of the sequence.
A generator is a special type of function that returns an iterator. We create a generator by using the function*
syntax. Inside the generator function, we use the yield
keyword to return each value in the sequence, and then the generator automatically pauses its execution until the next next()
method is called.
Here is an example of an iterator and a generator:
// Iterator exampleconst myArray = [1, 2, 3];const myIterator = myArray[Symbol.iterator]();console.log(myIterator.next()); // { value: 1, done: false }console.log(myIterator.next()); // { value: 2, done: false }console.log(myIterator.next()); // { value: 3, done: false }console.log(myIterator.next()); // { value: undefined, done: true }// Generator examplefunction* myGenerator() { yield 1; yield 2; yield 3;}const myIterator2 = myGenerator();console.log(myIterator2.next()); // { value: 1, done: false }console.log(myIterator2.next()); // { value: 2, done: false }console.log(myIterator2.next()); // { value: 3, done: false }console.log(myIterator2.next()); // { value: undefined, done: true }