HomeJAVASCRIPTWhat is a generator function?

What is a generator function?

A generator function in JavaScript (or Python, since both use similar concepts) is a special type of function that can pause its execution and later resume. Instead of returning a single value like a normal function, it yields multiple values over time, one at a time, which makes it very memory-efficient for handling large datasets or sequences.

Here’s a breakdown:


Key Features

  1. Defined using function* (asterisk) in JavaScript.
  2. Uses yield to produce a value and pause execution.
  3. Returns an iterator (an object with a next() method).
  4. Can maintain state between executions.

Example in JavaScript

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

const gen = numbers();

console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
  • value → the yielded value
  • done → indicates if the generator is finished

Use Cases

  • Iterating over large datasets without loading everything into memory.
  • Implementing lazy evaluation (compute values only when needed).
  • Creating infinite sequences (like Fibonacci numbers).

Share: 

No comments yet! You be the first to comment.

Leave a Reply

Your email address will not be published. Required fields are marked *