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:

SOLID series: The Open-Closed Principle

Today, we’ll be exploring the Open-Closed Principle: from the criticisms around it, its best use cases, and common misapplication.

Oyinkansola Awosan
May 16, 2025 â‹… 11 min read
Simplifying E2E Testing With Open Source AI Testing Tools

AI-powered e2e testing: Getting started with Shortest

Explore how AI-driven testing tools like Shortest, Testim, Mabl, and Functionize are changing how we do end-to-end testing.

Jude Miracle
May 16, 2025 â‹… 11 min read
profit center vs. cost center: How company structure affects engineering

Profit center vs. cost center: How company structure affects engineering

Examine the difference between profit vs. cost center organizations, and the pros and cons these bring for the engineering team.

Marie Starck
May 15, 2025 â‹… 4 min read
How to pass a TypeScript function as a parameter

How to pass a TypeScript function as a parameter

Explore how to pass functions and structured objects as parameters in TypeScript, including use cases, syntax, and practical scenarios.

Kealan Parr
May 15, 2025 â‹… 10 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