DEV Community

Imran Shaik
Imran Shaik

Posted on

1

What is generator function in JavaScript? and How does it work?

A generator function in JavaScript is special type of function that can be paused and resumed during its execution. It is defined using function* syntax and uses the yield keyword to produce values sequentially.

Key Characteristics of Generator function

  1. Define with function* :
function* generatorFunction(){
  yield 1;
  yield 2;
  yield 3;
  yield 4; 
}
Enter fullscreen mode Exit fullscreen mode

2.Returns an Iterator

  • when a generator function is called, it doesn't execute immediately. Instead, it returns an iterator object.
  • The iterator has a next() method that is used to control the execution.
    1. yieldkeyword:
  • The yieldkeyword is used to produce a value and pause the generator.
  • when next() is called again, the generator resumes execution from the point where it was paused.

Example of Generator Function:

function* generatorFunction(){
   console.log("start");
   yield 1;
   console.log("Resume");
   yield 2; 
   console.log("End");

}
const gen = generatorFuntion();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
Enter fullscreen mode Exit fullscreen mode

Output

start 
{value: 1, done: false}
Resume
{value: 2, done: false}
End
{Value: undefined, done: true}
Enter fullscreen mode Exit fullscreen mode

How it Works

  1. Exectution on next():
    • when next() is called for the first time, the generator starts execution and runs until the first yield.
    • it returns and object {value, done}, where:
      • value: The value produced by yield.
      • done: A boolean indicating whether the generator has completed
  2. Pause and Resume.
    • The function pauses execution when it encounters yield.
    • It resumes from the paused when next() is called again.
  3. completion:
    • when the generator function completes, the done property becomes true.

Sentry image

Make it make sense

Only get the information you need to fix your code that’s broken with Sentry.

Start debugging →

Top comments (0)

Gen AI apps are built with MongoDB Atlas

Gen AI apps are built with MongoDB Atlas

MongoDB Atlas is the developer-friendly database for building, scaling, and running gen AI & LLM apps—no separate vector DB needed. Enjoy native vector search, 115+ regions, and flexible document modeling. Build AI faster, all in one place.

Start Free

👋 Kindness is contagious

Take a moment to explore this thoughtful article, beloved by the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A heartfelt "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay