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:

Building a Full-Featured Laravel Admin Dashboard with Filament

Building a full-featured Laravel admin dashboard with Filament

Build scalable admin dashboards with Filament and Laravel using Form Builder, Notifications, and Actions for clean, interactive panels.

Kayode Adeniyi
Dec 20, 2024 â‹… 5 min read
Working With URLs In JavaScript

Working with URLs in JavaScript

Break down the parts of a URL and explore APIs for working with them in JavaScript, parsing them, building query strings, checking their validity, etc.

Joe Attardi
Dec 19, 2024 â‹… 6 min read
Lazy Loading Vs. Eager Loading

Lazy loading vs. Eager loading

In this guide, explore lazy loading and error loading as two techniques for fetching data in React apps.

Njong Emy
Dec 18, 2024 â‹… 5 min read
Deno logo over an orange background

How to migrate your Node.js app to Deno 2.0

Deno is a popular JavaScript runtime, and it recently launched version 2.0 with several new features, bug fixes, and improvements […]

Yashodhan Joshi
Dec 17, 2024 â‹… 7 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