Reputation:
I have been reading about iterators and generators a lot lately and from what I have read/seen around, it seems like generators are a syntactic sugar for generating iterators. However, in some code examples, I have also seen the returned value of these generators being used as an iterable. For example:-
function* sampleGenerator() {
yield 1
yield 2
yield 3
}
const it = sampleGenerator()
for (const n of it) {
console.log(n)
}
I assume that in the for...of
loop, the object after the of
is an iterable (e.g. arrays, strings etc.). Thus, I am a bit confused about whether the return type is an iterator or an iterable.
Upvotes: 2
Views: 42
Reputation: 3417
As you can read in the documentation:
A generator object is both iterator and iterable:
let aGeneratorObject = function* () {
yield 1;
yield 2;
yield 3;
}();
console.log(typeof aGeneratorObject.next);
// "function", because it has a next method, so it's an iterator
console.log(typeof aGeneratorObject[Symbol.iterator]);
// "function", because it has an @@iterator method, so it's an iterable
console.log(aGeneratorObject[Symbol.iterator]() === aGeneratorObject);
// true, because its @@iterator method returns itself (an iterator), so it's an well-formed iterable
console.log([...aGeneratorObject]);
// [1, 2, 3]
Upvotes: 3