Generators in JavaScript

Last Updated: 22nd October 2025


A generator is a special kind of function that can pause and resume its execution.
It doesn’t run all at once like normal functions.

Hinglish Tip 🗣: Normal function ek hi baar start se end tak chalta hai,lekin generator function ruk kar baad mein wapas chalu ho sakta hai! ⏸▶️


✏️ Syntax

A generator function is declared using function* (note the *).

function* generatorFunction() {
  yield "Hello";
  yield "World";
}

When you call a generator, it does not execute immediately instead it returns a generator object (iterator).

const gen = generatorFunction();
console.log(gen.next()); // { value: "Hello", done: false }
console.log(gen.next()); // { value: "World", done: false }
console.log(gen.next()); // { value: undefined, done: true }

yield : Pauses the function and returns a value temporarily next(): Resumes the function execution from where it left off

Hinglish Tip 🗣: Socho yield jaise ek pause button,aur next() jaise play button jo wapas wahi se start karta hai!


Example 1:

function* names() {
  yield "Amit";
  yield "Sneha";
  yield "Rahul";
}

for (let name of names()) {
  console.log(name);
}

Example 2:

function* numbers() {
  yield 1;
  yield 2;
  return 3;
}

const n = numbers();
console.log(n.next()); // { value: 1, done: false }
console.log(n.next()); // { value: 2, done: false }
console.log(n.next()); // { value: 3, done: true }

💡 Quick Practice

  • Write a generator that yields the first 5 even numbers.
  • Create a generator that yields letters A–Z.
  • Make an infinite generator that yields multiples of 3.
  • Use a generator inside a for...of loop to print 1 to 10.