Iterators and Generators
Iterators
- Data structures like Arrays have their own built in iterators
- You can build your own iterators for data types that don't have it built in with
[Symbol.iterator]
Generators
- Generator functions provide alternatives to iterators, allows you to define an iterative algorithm by writing a single function that is not executed continuously. Would need to call .next() to get the next value
- Uses the * keyword
function *main() {
yield 1;
yield 2;
return "Finished";
}
var iterator = main()
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log(iterator.next());
console.log([...main()]);