JS Tip of the Day: Yield Many With yield*

Yield Many With yield*
Version: ES2015
Level: Intermediate

When you yield a value from a generator with yield it provides that value as an iteration value when the generator object iterator is used in iteration. When yielding multiple values, you might consider handling this through a loop.

function * gen () {
    let nums = [1, 2, 3];
    for (let num of nums) {
        yield num;
    }
}

for (let value of gen()) {
    console.log(value);
}
/* logs:
1
2
3
*/

If you’re looping through an iterable this way, you can automatically yield every value in that iterator using yield*. yield* is a shortcut that will automatically take the values of an iterable and yield them out individually from the current generator function.

function * gen () {
    let nums = [1, 2, 3];
    yield * nums;
}

for (let value of gen()) {
    console.log(value);
}
/* logs:
1
2
3
*/

Note that if you were try to yield an iterable without the *, you’d get the entire iterable in the iteration rather than its individual values.

function * gen () {
    let nums = [1, 2, 3];
    yield nums;
}

for (let value of gen()) {
    console.log(value);
}
/* logs:
[1, 2, 3]
*/

The use of yield* instead lets you spread out the iterable between multiple iterations, not unlike using the spread operator (...) in arrays or argument lists.

More info: