ES6 Javascript: Generators

AnKiT KaMbOj
1 min readNov 1, 2018

--

Generator functions:
While custom iterators are a useful tool, their creation requires careful programming due to the need
to explicitly maintain their internal state. Generator functions provide a powerful alternative:
they allow you to define an iterative algorithm by writing a single function whose execution is not continuous.
Generator functions are written using the syntax. When called initially, generator functions do not
execute any of their code, instead returning a type of iterator called a Generator.
When a value is consumed by calling the generator’s next method, the Generator function executes
until it encounters the yield keyword.

The function can be called as many times as desired and returns a new Generator each time,
however each Generator may only be iterated once.

We can now adapt the example from above. The behavior of this code is identical,
but the implementation is much easier to write and read.

Example:
function* makeRangeIterator(start = 0, end = Infinity, step = 1) {
let loopCount = 0;
for (let i = start; i < end; i += step) {
loopCount++;
yield i;
}
return loopCount;
}

var result=makeRangeIterator(1,10,2);
console.log(result.next());
console.log(result.next());

--

--

AnKiT KaMbOj
AnKiT KaMbOj

No responses yet