5

This is a new technology, part of the ECMAScript 2015 (ES6) standard . This technology's specification has been finalized, but check the compatibility table for usage and implementation status in various browsers.

The function* declaration (function keyword followed by an asterisk) defines a generator function, which returns a Generator object.

You can also define generator functions using the GeneratorFunction constructor and a function* expression.

Example given:

function* idMaker(){
  var index = 0;
  while(index < 3)
    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); // undefined
// ...

MDN function*

Question:

While the example is understandable, why should I be using it over something like this:

var index = 0;
function idMaker(){
  return (index < 2) ? index++: undefined;
}

or even (to answer the index scope comment):

var idMaker = function(){
  this.index = 0;
  this.next = function(){
    var res = (this.index < 3) ? this.index++: undefined;
    return { value: res };
  };
}

var gen = new idMaker();

console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
Community
  • 1
  • 1
kemicofa ghost
  • 16,349
  • 8
  • 82
  • 131
  • That simple example is only to be used to show syntax and calling conventions. In real life, you wouldn't use a loop either, you'd just do `console.log(1, 2, 3)`… The comparison between generators/loops is flawed in this case, but I hope my answer to the duplicate is more useful. – Bergi Sep 01 '15 at 15:59
  • Generators make it very easy to create iterators :) – Felix Kling Sep 01 '15 at 17:42

0 Answers0