What are Generators in EcmaScript 6?

Genrators, a buzzword now a days, are a part of EcmaScript 6 Harmony proposal and still in experimental phase. Generators have made their way through Chrome 29, Firefox Gecko and Opera 16 release.

Generators are functions which have different behaviour as they can save their internal state, they can be paused or resumed when we want and they can be passed values to change the internal state of the generator.

Lets see a very simple generator function:

function* increment(x){
    yeild x++;
};

There are two new things in the above function, firstly the * symbol after the function keyword which is just the syntax of defining a generator function and secondly the yeild keyword which pauses the function execution and returns the value when encountered. Each call to the generator's next function executes the function upto the next yeild statement.

When the increment function is executed, it wil return a generator object with various methods like next and send. We will look into each of it in detail further up.

//Executing the above increment function

var inc = increment(1);
console.log(inc.next()); //Output 2
console.log(inc.next()); //Output 3
console.log(inc.next()); //Output 4

inc.send(10); //passing value in between

console.log(inc.next()); //Output 11
console.log(inc.next()); //Output 12
console.log(inc.next()); //Output 13    

next()

The next() function executes the generator function upto the next yeild statement and returns the value. The yeild keyword actually returns an object with value and done properties. value represents the actual value being returned and the done which is a boolean represents if the generator has finished.

send()

The send() function is used to pass the values to generator. The value passed acts as the value from the last yeild statement.

So this was a getting started like intro to Generators. In next post, we will look more into depth and what is the significance of Generators in Node.js.

comments powered by Disqus