Generator returns an object on which we can call next().

Every invocation of next() will return an object containing returned value and status of generator execution.

value property will contain the value and done property will be true or false mentioning generator’s execution status.

When done becomes true, generator stops and won’t generate any more values. { value: Any, done: true|false }

Sample code: ( jsfiddle link : generator example ) function * generator() { console.log('First execution.'); yield 'Yield First execution, saved the state and exit'; console.log('Second execution will be on next() call.'); yield 'Yield second execution, saved the state and exit'; } const generatorObj = generator(); // After below execution, generator will yield value, return below object and pause execution. // {value: 'Yield First execution, saved the state and exit', done: false} setTimeout(() => console.log(generatorObj.next()), 1000); // After below execution, generator will yield value, return below object and pause execution. // {value: 'Yield First execution, saved the state and exit', done: false} setTimeout(() => console.log(generatorObj.next()), 3000); // After below execution, generator will yield value, return below object and close execution. // {value: undefined, done: true} setTimeout(() => console.log(generatorObj.next()), 5000);

Below example shows the different state of a generator during its execution of how it gets suspended when it is yielded, resumes on next() call and then gets closed after all execution:





If we use return then it will not execute any code present after the return statement.

Sample code: ( jsfiddle link: generator with return statement ) function * generator() { console.log('First execution.'); yield 'Yield First execution, saved the state and exit'; return 'Execution ends here due to return and will not execute rest of the codes.'; // All below codes will not get executed. yield 'Yield second execution, saved the state and exit'; } const generatorObj = generator(); // After below execution, generator will yield value, return below object and pause execution. // {value: 'Yield First execution, saved the state and exit', done: false} setTimeout(() => console.log(generatorObj.next()), 1000); // After below execution, generator will yield value, return below object and completes the execution. // {value: 'Execution ends here due to return and will not execute rest of the codes.', done: true} setTimeout(() => console.log(generatorObj.next()), 3000); // generator execution is already completed so it will just return value as undefined and done as true. // {value: undefined, done: true} setTimeout(() => console.log(generatorObj.next()), 5000);