Search code examples
javascriptgeneratoryield

use yield inside another yield


I would like to use generator to print the content of an array, however yield inside another yield is confusing to me

let myArray = ["a", "b", "c"]

function* line(array){
  yield "my array"
  array.forEach(function*(v){yield v})
}

console.log(Array.from(line(myArray)))

is there a way to print the "a", "b" and "c" each in a new line with the code above?

expected output

my array
a
b
c

Solution

  • Being explicit, with a visible inner for(of):

    let myArray = ["a", "b", "c"]
    
    function* line(array) {
      yield "my array";
    
      for( const ch of array ) {
        yield ch;
      }
    }
    
    console.log(Array.from(line(myArray)))

    Using implicit iteration with yield*:

    let myArray = ["a", "b", "c"]
    
    function* line(array) {
      yield "my array";
      yield* array;
    }
    
    console.log(Array.from(line(myArray)))

    ...basically, yield* $iterable; is the same thing as doing for( const v of $iterable ) yield v;.