JavaScript/Generators

From Wikibooks, open books for an open world
Jump to navigation Jump to search
Previous: Code structuring Index Next: Contributors


Generators are part of the ECMAScript 6 language specification. Firefox has supported the ECMAScript 6 compliant syntax for generators since 2013-12-10.[1] Node.js (server-side JavaScript) also has supported ES6 generator syntax[2] since 2013-05-15.[citation needed]


example

function* vehicle(){
  var index = 0;
  while (index < 4)
    yield index++;
}

var firetruck = vehicle();
var car = vehicle();

console.log(car.next().value); // 0
console.log(car.next().value); // 1
console.log(firetruck.next().value); // 0
console.log(car.next().value); // 2
console.log(firetruck.next().value); // 1
console.log(car.next().value); // 3
console.log(car.next().value); // undefined


The function* keyword creates a generator function.[3]

Further reading

(FIXME: Say a few more words about generators. Perhaps use some or all of the following as references:

"Generators in Node.js: Common Misconceptions and Three Good Use Cases". "Coroutines no, generators yes. Why coroutines won’t work on the Web". "What Is This Thing Called Generators?". "callbacks vs generators vs coroutines".)

References


Previous: Code structuring Index Next: Contributors