Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

What are Generator Functions in JavaScript



Generator Functions allows execution of code in between when a function is exited and resumed later. So, generators can be used to manage flow control in a code. Cancel asynchronous operations easily since execution can be paused anytime.

Here’s the syntax; do not forget to add an asterisk after the “function” keyword. You can add an asterisk using any of the following −

function *myFunction() {}
// or
function* myFunction() {}
// or
function*myFunction() {}

Example

Let’s see how to use a generator function

Live Demo

<html>
   <body>
      <script>
         function* display() {
            var num = 1;
            while (num < 5)
            yield num++;
         }
         var myGenerator = display();

         document.write(myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
         document.write("<br>"+myGenerator.next().value);
      </script>
   </body>
</html>
Updated on: 2020-06-16T06:27:28+05:30

255 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements