1

It is pretty straight forward to get what 'yield' is doing in a generator function in the example below. But apparently there is another version of it 'yield*'

function * loop(times){
   while(times){
     times--;
     yield times;
   }
}

let result = loop(2);
result.next() // {value: 1, done:false} 

Can someone explain the difference between'yield' and 'yield*' ?

Hivaga
  • 1,548
  • 2
  • 12
  • 23
  • 1
    "The `yield*` expression is used to delegate to another generator or iterable object." - [https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield*) – frobinsonj Jun 21 '19 at 18:13
  • Essentially, `yield * iterable;` and `for (const value of iterable) yield value;` do the same thing. – Patrick Roberts Jun 21 '19 at 18:28

1 Answers1

2

The yield* operator delegates iteration to another iterable, as demonstrated below:

// this function is more or less a no-op
function * iterate (iterable) {
  yield * iterable;
}

function * loop (times) {
   while (times) {
     times--;
     yield times;
   }
}

console.log('accepts iterables');
for (const value of iterate([1, 2, 3])) {
  console.log(value);
}

console.log('accepts generator iterators');
for (const value of iterate(loop(3))) {
  console.log(value);
}

const iterator = [1, 2, 3][Symbol.iterator]();

// skip first value
iterator.next();

console.log('accepts partially consumed iterators');
for (const value of iterate(iterator)) {
  console.log(value);
}
Patrick Roberts
  • 40,065
  • 5
  • 74
  • 116