Graduate Program KB

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()); //{ value: 1, done: false }
    console.log(iterator.next()); //{ value: 2, done: false }
    console.log(iterator.next()); //{ value: 'Finished', done: true }
    console.log(iterator.next()); //{ value: undefined, done: true }
    console.log([...main()]); // [1,2]