generator javascript code example

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: javascript generator function

function* idMaker() {
  var index = 0;
  while (true)
    yield index++;
}

var gen = idMaker();

console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
// ...

Example 3: 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)

Example 4: function generator js

function* name([param[, param[, ... param]]]) {
   statements
}

Example 5: JavaScript — Generators

function* makeRangeIterator(start = 0, end = 100, step = 1) {
    let iterationCount = 0;
    for (let i = start; i < end; i += step) {
        iterationCount++;
        yield i;
    }
    return iterationCount;
}