JavaScript Generator

JavascriptWeb DevelopmentObject Oriented Programming

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 −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .sample {
      font-size: 18px;
      font-weight: 500;
<h1>JavaScript Generator</h1>
<div class="sample"></div>
<button class="Btn">CLICK HERE</button>
Click on the above buttons to call the generator function to generate some result
   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 += + "<br>";
      sampleEle.innerHTML += + "<br>";
      sampleEle.innerHTML += + "<br>";
      sampleEle.innerHTML += + "<br>";


On clicking the ‘CLICK HERE’ button −

Published on 08-May-2020 14:56:53