Skip to content

Instantly share code, notes, and snippets.

@dhei
Last active December 27, 2017 17:32
Show Gist options
  • Save dhei/5e05380f4efa1de16f260d14471a0dcf to your computer and use it in GitHub Desktop.
Save dhei/5e05380f4efa1de16f260d14471a0dcf to your computer and use it in GitHub Desktop.
es6 generator

Why value from return statement is ignored when iterating through a generator

If you are iterating through an iterator, using a for ... of loop or something like Array.from, the return value is going to be ignored. In other words, the value included in the end-of-iteration object (whose property done is true) is ignored.

function *gen(){
 const val = yield 4;
 return val * 2;
}

for (let value of gen()) {
  console.log(value);
}

// output: 4

MDN function* documenation explained it very well:

A return statement in a generator, when executed, will make the generator done. If a value is returned, it will be passed back as the value. A generator which has returned will not yield any more values.


Reference:

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment