1

I am writing the simple function of generator

function simpleGenerator(){
  yield "first";
  yield "second";
  yield "third";
};
var g = simpleGenerator();
console.log(g.next());

it is giving for the line of yield --

SyntaxError: missing ; before statement

i am unable to get the reason for showing error... if i use return like

function simpleGenerator(x){
 while(true){
  var a=x*2;
  return a;
 }
}
var g = simpleGenerator(2);
console.log(g);

It is working properly,

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Ammar Hayder Khan
  • 1,287
  • 4
  • 22
  • 49

1 Answers1

5

Generator functions have to be defined like this

function * simpleGenerator() {    # Note the `*` after `function` keyword
    yield "first";
    yield "second";
    yield "third";
};
var g = simpleGenerator();
console.log(g.next());
# { value: 'first', done: false }

Quoting from the ECMA 6's Harmony page for Generator functions,

The function syntax is extended to add an optional * token:

FunctionDeclaration:
    "function" "*"? Identifier "(" FormalParameterList? ")" "{" FunctionBody "}"   FunctionExpression:
    "function" "*"? Identifier? "(" FormalParameterList? ")" "{" FunctionBody "}"

A function with a * token is known as a generator function. The following two unary operators are only allowed in the immediate body of a generator function (i.e., in the body but not nested inside another function):

AssignmentExpression:
    ...
    YieldExpression

YieldExpression:
    "yield" ("*"? AssignmentExpression)?

An early error is raised if a yield or yield* expression occurs in a non-generator function.YieldExpression:

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
  • @lyschoening It is optional because you can drop `*` to define a normal function. – thefourtheye May 06 '14 at 07:13
  • you are right. I still don't know if that is the cause of the issue here because the `yield` keyword already existed in Javascript 1.7 as implemented by Mozilla and the enclosing function did not require a `*` back then. – lyschoening May 06 '14 at 07:17
  • @lyschoening This is the standard going forward. So, if FF does differently it is a non-standard feature or not a ECMA standard complaint feature :-) – thefourtheye May 06 '14 at 07:19
  • I wonder what browser OP is using. There is a SyntaxError in Chrome when the flag is missing, but it is a `SyntaxError: Unexpected string` – lyschoening May 06 '14 at 07:28
  • I get: SyntaxError: function statement requires a name – ealfonso Aug 01 '14 at 19:55
  • @erjoalgo Which environment is that? – thefourtheye Aug 02 '14 at 07:39
  • I was using iceweasel. Probably the javascript version was pre-yield support. I couldn't find a sensible way to iterate through one of these generators, so I ended up skipping yield altogether. – ealfonso Aug 02 '14 at 08:04
  • @erjoalgo Try using the latest Node.js development version, with harmony options :-) – thefourtheye Aug 02 '14 at 11:09