Explain Generator functions in JavaScript?


Generators

JavaScript supports Generator functions and Generator Objects. A generator function is the same as a normal function, but whenever it needs to generate a value it uses the 'yield' keyword rather than 'return'. The 'yield' keyword halts the function execution and sends a value back to the caller. It has an ability that it can resume the functionality from where it is left off. 

syntax

function* generator(){
   yeild 1;
   yeild 2;
}

Example

In the following example, using a generator function, natural numbers 10,9 and 8 were printed. Instead of printing each number individually we can run a for loop and print whatever numbers we need.  

Live Demo

<html>
<body>
<script>
   function * number() {
      var num = 10;
      while (true) {
         yield num--;
      }
   }
   var gen = number();
   document.write(gen.next().value);
   document.write("</br>");
   document.write(gen.next().value);
   document.write("</br>");
   document.write(gen.next().value);
</script>
</body>
</html>

Output

10
9
8

Updated on: 30-Jul-2019

496 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements