generator example javascript

Example 1: generators in javascript

function* g(){    //or function *g(){}
  console.log("First");
  yield 1;
  console.log("second");
   yield 2;
  console.log("third");
} 
let generator=g();
generator.next();
generator.next();

Example 2: js generator

function* fibonacci() {
  var a = yield 1;
  yield a * 2;
}

var it = fibonacci();
console.log(it);          // "Generator {  }"
console.log(it.next());   // 1
console.log(it.send(10)); // 20
console.log(it.close());  // undefined
console.log(it.next());   // throws StopIteration (as the generator is now closed)