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
// ...
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);