What is Function in JavaScript



The function* declaration is used to define a generator function. It returns a Generator object. 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.

Syntax

Here’s the syntax −

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

Let’s see how to use generator function

Example

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-12T09:02:44+05:30

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements