JavaScript Generators Sending Values to Generator


It is possible to send a value to the generator by passing it to the next() method.

function* summer() {
    let sum = 0, value;
    while (true) {
        // receive sent value
        value = yield;
        if (value === null) break;

        // aggregate values
        sum += value;
    return sum;
let generator = summer();

// proceed until the first "yield" expression, ignoring the "value" argument;

// from this point on, the generator aggregates values until we send "null";;;

// close the generator and collect the result
let sum =;  // 111