JavaScript Generator


A generator function uses the yield keyword to generate results and maintain its state even after returning so that the next time when it is called it can resume immediately from the last yield run. Each call to the generator function will send a value back to the caller.

Following is the code for the Generator function in JavaScript −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .sample {
      font-size: 18px;
      font-weight: 500;
   }
</style>
</head>
<body>
<h1>JavaScript Generator</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
<h3>
Click on the above buttons to call the generator function to generate some result
</h3>
<script>
   let sampleEle = document.querySelector(".sample");
   function* generate(num) {
      yield 2 * num;
      yield 3 * num;
      yield 4 * num;
      yield 5 * num;
   }
   let Gen = generate(8);
   document.querySelector(".Btn").addEventListener("click", () => {
      sampleEle.innerHTML += Gen.next().value + "<br>";
      sampleEle.innerHTML += Gen.next().value + "<br>";
      sampleEle.innerHTML += Gen.next().value + "<br>";
      sampleEle.innerHTML += Gen.next().value + "<br>";
   });
</script>
</body>
</html>

Output 

On clicking the ‘CLICK HERE’ button −

Updated on: 08-May-2020

209 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements