jskatas.org Continuously Learn JavaScript. Your Way.

Generator: yield expressions

The yield keyword is used to pause and resume a generator function

Generator - yield is used to pause and resume a generator function

converting a generator to an array (using Array.from) resumes the generator until all values are received
function* generatorFunction() { yield 'hello'; yield 'world'; } let values = Array.from(generatorFunction); assert.deepEqual(values, ['hello', 'world']);

after the first generator.next() call

the value is "hello"
function* generatorFunction() { yield 'hello'; yield 'world'; } const generator = generatorFunction(); const {value} = generator.next; assert.equal(value, 'hello');
and done is false
function* generatorFunction() { yield 'hello'; yield 'world'; } const generator = generatorFunction(); const {done} = generator; assert.equal(done, false);

after the second next() call

value is "world"
function* generatorFunction() { yield 'hello'; yield 'world'; } const generator = generatorFunction(); generator.next(); const secondItem = generator.next(); let {value} = secondItem; assert.equal(value, 'world');
and done is still false
function* generatorFunction() { yield 'hello'; yield 'world'; } const generator = generatorFunction(); generator.next(); const secondItem = generator.next(); const done = secondItem; assert.equal(done, false);

after stepping past the last element, calling next() that often

done property equals true, since there is nothing more to iterator over
function* generatorFunction() { yield 'hello'; yield 'world'; } const generator = generatorFunction(); generator.next(); generator.next(); let done = generator.done; assert.equal(done, true);

Links

Describing the `yield` keyword.

Required Knowledge

Related Katas

Generator

Difficulty Level

TBD

First Published

5 June 2015

Stats

6 tests to solve