2021-04-27
2239
#vanilla javascript
Felix Gerschau
45401
Apr 27, 2021 â‹… 7 min read

JavaScript iterators and generators: A complete guide

Felix Gerschau Felix is a frontend developer at Fitogram in Cologne, Germany.

Recent posts:

how to use the ternary operator in javascript

How to use the ternary operator in JavaScript

Add to your JavaScript knowledge of shortcuts by mastering the ternary operator, so you can write cleaner code that your fellow developers will love.

Chizaram Ken
Feb 21, 2025 â‹… 7 min read
Using tsup To Bundle Your TypeScript Package

Using tsup to bundle your TypeScript package

Learn how to efficiently bundle your TypeScript package with tsup. This guide covers setup, custom output extensions, and best practices for optimized, production-ready builds.

Muhammad Ali
Feb 20, 2025 â‹… 7 min read
how to use react higher order components

How to use React higher-order components

Learn the fundamentals of React’s high-order components and play with some code samples to help you understand how it works.

Hussain Arif
Feb 20, 2025 â‹… 10 min read
dependency inversion principle

Understanding the dependency inversion principle (DIP)

Learn about the dependency inversion principle (DIP), its importance, and how to implement it across multiple programming languages.

Samuel Olusola
Feb 20, 2025 â‹… 8 min read
View all posts

5 Replies to "JavaScript iterators and generators: A complete guide"

  1. Nice article. I was a little confused by the output shown for the `throw` example, so I tried running a modified version it in the browser.

    “`
    function* errorGenerator() {
    try {
    yield ‘one’;
    yield ‘two’;
    } catch(e) {
    console.error(e);
    }
    yield ‘three’;
    yield ‘four’;
    }

    const errorIterator = errorGenerator();

    console.log(errorIterator.next()); // outputs “{ value: ‘one’, done: false }”
    console.log(errorIterator.throw(‘Bam!’)); // outputs “Bam!” AND “{ value: ‘three’, done: false }”
    console.log(errorIterator.next()); // outputs “{ value: ‘four’, done: false }”
    console.log(errorIterator.next()); // outputs “{ value: undefined, done: true }”
    “`

    It appears that the throw doesn’t actually end the generator, but rather simulate an exception thrown, which is caught by the catch block, then continues the rest of the function normally.

Leave a Reply