Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

JavaScript Essentials - Generators

Introduction to generators and their use cases

Generators are a powerful feature in JavaScript that allow you to define an iterative algorithm by writing a function whose execution is not continuous. This tutorial covers the basics of generators and their use cases.

Key Points:

  • Generators can pause and resume their execution.
  • They are useful for handling asynchronous operations and creating iterators.
  • The yield keyword is used to pause the execution of a generator function.

Creating a Generator

Generators are defined using the function* syntax. The yield keyword is used to pause and resume the generator's execution.


function* simpleGenerator() {
    yield 'First value';
    yield 'Second value';
    yield 'Third value';
}

const gen = simpleGenerator();
console.log(gen.next().value); // Output: First value
console.log(gen.next().value); // Output: Second value
console.log(gen.next().value); // Output: Third value
console.log(gen.next().value); // Output: undefined
                

Iterating with Generators

Generators are particularly useful for creating iterators. You can use the for...of loop to iterate over the values yielded by a generator.


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

const gen = numberGenerator();
for (const num of gen) {
    console.log(num); // Output: 1, 2, 3
}
                

Use Case: Infinite Sequences

Generators can be used to create infinite sequences. For example, you can create a generator that yields an infinite sequence of numbers.


function* infiniteNumbers() {
    let num = 1;
    while (true) {
        yield num++;
    }
}

const gen = infiniteNumbers();
console.log(gen.next().value); // Output: 1
console.log(gen.next().value); // Output: 2
console.log(gen.next().value); // Output: 3
                

Use Case: Asynchronous Operations

Generators can also be used to handle asynchronous operations in a more synchronous-looking manner. By using yield to pause execution until a Promise resolves, you can simplify asynchronous code.


function* fetchData() {
    const response = yield fetch('https://api.example.com/data');
    const data = yield response.json();
    console.log(data);
}

const gen = fetchData();
const promise = gen.next().value;
promise.then(response => gen.next(response).value)
       .then(data => gen.next(data));
                

Summary

In this tutorial, you learned about generators in JavaScript. Generators allow you to write functions that can pause and resume their execution, making them useful for creating iterators and handling asynchronous operations.