0

This Javascript code gives a syntax error ("unexpected identifier") on the "yield" line in chrome version 70.0.3538.110:

function foo() {
  var arr = [0];
  yield arr;
}

This has no error:

function foo() {
  var arr = [0];
  return arr;
}

This also has no error:

function foo() {
  var arr = [0];
  yield [arr];
}

I can yield the [] version and subscript it, but is there a cleaner way?

I want to yield the array many times during the execution of the function, as it gets mutated.

Ele
  • 31,191
  • 6
  • 31
  • 67
dfrankow
  • 16,533
  • 35
  • 121
  • 177
  • 6
    Are you using `yield` inside a generator [function*](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*)? If you are attempting to use `yield` inside a normal `function` you will get an error. It is specifically used with generator functions. – Alexander Staroselsky Dec 06 '18 at 23:32
  • 2
    Can you clarify how you would use `foo()` specifically? Methods like [next()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Generator/next) to extract yielded values are specific to Generator functions. They return an object that looks like `{ value: 1, done: false }`. You wouldn't be able use `next()` on a non-Generator function. – Alexander Staroselsky Dec 06 '18 at 23:39
  • @AlexanderStaroselsky You are right: it needs to be a function*, and it is a dup of that question. Thanks! I'll close this as a dup. – dfrankow Dec 07 '18 at 17:09

0 Answers0