Skip to content
Iterators and Generators
step 1/5

Reading — step 1 of 5

Learn

~1 min readIteration and Generators

JavaScript has a formal iterator protocol: any object with a next() method that returns { value, done } is iterable.

javascript

The [Symbol.iterator] is the magic protocol method. for...of, spread, destructuring all use it.

Generators are a much easier way to make iterators:

javascript

The function* declares a generator. yield pauses, returning a value; the function resumes on the next .next() call.

Generators have state:

javascript

Async iteration with for await:

javascript

This is what powers things like Node's fs.readFile streams, GraphQL subscriptions, and message queue consumers.

Discussion

Ask a question, share an insight, or help someone who’s stuck.

Sign in to post a comment or reply.

Loading…