ES6 Generators VS ES5 Generator

generator function

generator function

We know that ES6 now supports a new type of function which is called the generator function, so today we will learn how to write a generator function in ES6 and then will learn how to achieve the same in ES5.

ES6 generator

In contrast, a generator is a function that can stop midway and then continue from where it stopped. A generator function produces a sequence of results instead of a single value, i.e you generate ​a series of values. Each time a generator encounters a yield, it “returns” the value specified after it and pauses the execution until .next() is called again.

In the example below, you can see if you call .next().value you get a new Fibonacci value each time.

ES 5 generator

As we know generator function came in the ES6 version of JS, so we can’t use the same syntax as we did in the above example with ES5. To achieve similar kinds of generators in ES5 we can use the concept of closures. I tried to create a Fibonacci generator using a closure in the below code.

Code explanation:

  • createFibonacciGenerator() is a function which returns a function which is used to generate the series, in the standard term we call it closure.
  • inside createFibonacciGenerator() we created 2 private variables num1 and num2.
  • Now we created an anonymous inner function, which we are returning to the user. Users can use this returned method to generate a new Fibonacci value each time it runs.
  • The anonymous method internally uses the private variable num1 and num2 to generate the next Fibonacci value
const result = num1;
[num1, num2] = [num2, num1 + num2];

[num1, num2] = [num2, num1 + num2];
means num1 = num2 and num2 = num1 + num2
for example if num1=3 and num2=5 then
num1=5 and num2 =(3+5)

  • And finally returning the result variable from the inner function as new value whenever the user calls the inner function.

Leave a Reply

Close Bitnami banner