It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 78 – JavaScript Generators

Generators are a special class of functions that can be paused and resumed. They’re particularly useful when working with sequences, lazy evaluation, or asynchronous flows.


What Is a Generator?

A generator is a function declared with an asterisk (function*) and uses the yield keyword to return values one at a time, pausing in between.

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

Calling countToThree() returns an iterator, not the values themselves.


Using a Generator

const counter = countToThree();

console.log(counter.next()); // { value: 1, done: false }
console.log(counter.next()); // { value: 2, done: false }
console.log(counter.next()); // { value: 3, done: false }
console.log(counter.next()); // { value: undefined, done: true }

Each call to .next() returns an object with value and done.


Use Case Example – ID Generator

function* idGenerator() {
  let id = 1;
  while (true) {
    yield id++;
  }
}

const gen = idGenerator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3

This creates an infinite sequence of IDs, only producing a new value when requested.


Advantages of Generators

  • Memory efficient: Useful for large or infinite sequences.
  • Lazy evaluation: Generates values only when needed.
  • Pause/resume: Great for complex flows.

Try Your Hand

Challenge: Create a generator that yields the Fibonacci sequence.

function* fibonacci() {
  let [a, b] = [0, 1];
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const fib = fibonacci();
console.log(fib.next().value); // 0
console.log(fib.next().value); // 1
console.log(fib.next().value); // 1
console.log(fib.next().value); // 2
console.log(fib.next().value); // 3

Summary

  • Generators are declared using function*.
  • They yield values using the yield keyword.
  • Calling .next() resumes execution until the next yield.