What Does yield* Do in JavaScript?

The JavaScript yield* expression can be used inside a generator function to specify another generator or an iterable object that you can yield values from. It works by iterating over the operand and yielding each value returned by it. For example:

function* bar() {
  yield 2;
  yield 3;
}

function* foo() {
  yield 1;
  yield* bar();
  yield 4;
}

const iterator = foo();

console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: 3, done: false}
console.log(iterator.next()); // {value: 4, done: false}
console.log(iterator.next()); // {value: undefined, done: true}

In the example above you can see that when next() is called on foo():

  • In case of yield, the value of the expression following the yield keyword is returned, and;
  • In case of yield*, yield is delegated to bar(), and foo() yields each value returned by it (till it's closed — i.e. when done returned by bar() is true).

This works in a similar way with other kinds of iterables (such as arrays, strings, or arguments objects):

function* foo(...args) {
  yield* [1, 2];
  yield* '34';
  yield* args;
}

const iterator = foo(5, 6);

console.log(iterator.next()); // {value: 1, done: false}
console.log(iterator.next()); // {value: 2, done: false}
console.log(iterator.next()); // {value: '3', done: false}
console.log(iterator.next()); // {value: '4', done: false}
console.log(iterator.next()); // {value: 5, done: false}
console.log(iterator.next()); // {value: 6, done: false}
console.log(iterator.next()); // {value: undefined, done: true}

This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.