When a generator function is called, the body of the function does not execute straight away; instead, it returns a generator-iterator object. Each call to the generator-iterator's next() method will execute the body of the function up to the next yield statement and return its result. When either the end of the function or a return statement is reached, a StopIteration exception is thrown.
For example, the following fib() function is a Fibonacci number generator, that returns the generator when it encounters the yield statement:
function fib() { var fibNum = 0, j = 1; while (true) { yield fibNum; var t = fibNum; fibNum = j; j += t; } }To use the generator, simply call the next() method to access the values returned by the function:
var gen = fib(); for (var i = 0; i < 10; i++) { document.write(gen.next() " "); }
You can't start a generator at an arbitrary point; you must start it with next() before you can send() it a specific value. Note that calling send(undefined) is equivalent to calling next(). However, starting a newborn generator with any value other than 'undefined' when calling send() will result in a TypeError exception.