Delegating yield in JavaScript

Tuesday, September 1, 2015

In an earlier post we looked at generator functions in JavaScript.

Generator methods can call into other generator methods, and yield values received from another generator method. A generator can even unroll or flatten another generator’s result into it’s own iterator using yield*. As an example, consider the following generator method which yields two strings.

let inner = function*() {
    yield "Hello";
    yield "there";

The next generator will call the inner generator using the yield* syntax.

let outer = function*() {
    yield* inner();
    yield "World";

The yield* syntax will flatten the result from inner so that the outer generator yields three strings.

var result = Array.from(outer());
expect(result).toEqual(["Hello", "there", "World"]);

If the outer generator used yield instead of yield*, the result of outer would be inner’s iterator, followed by the string “World”.

gravatar Steinar Herland Friday, September 4, 2015
Does this mean that yield* is syntactical sugar for (c# syntax) "foreach(var item in inner()) {yield item;}"?
gravatar Scott Friday, September 4, 2015
@Steinar: Yes!
Comments are closed.

My Pluralsight Courses

K.Scott Allen OdeToCode by K. Scott Allen
What JavaScript Developers Should Know About ECMAScript 2015
The Podcast!