A Simple Guide to Understanding Javascript (ES6) Generators

Rajesh Babu
May 4, 2018 · 9 min read
Image for post
Image for post
Image for post
Image for post
Generator Turbine
new Map([[1, 2]])[Symbol.iterator]() // MapIterator {1 => 2}
“hi”[Symbol.iterator]() // StringIterator {}
[‘1’][Symbol.iterator]() // Array Iterator {}
new Set([1, 2])[Symbol.iterator]() // SetIterator {1, 2}
Image for post
Image for post

Introduction

Image for post
Image for post
Basic generator function

Lifecycle of a Generator Function

Image for post
Image for post
Life-cycle of a Generator Function

Assigning Yield to a Variable

Image for post
Image for post
Assigning yield to a variable

Passing Arguments to the next() Method

Image for post
Image for post
Passing arguments to the next()

Explanation:

Passing Yield as an Argument of a Function

Image for post
Image for post
Yield as an argument of a function

Explanation

Yield with a Function Call

Image for post
Image for post
Yield calling a function

Yield with Promises

Image for post
Image for post
Yield with promises

Yield*

Image for post
Image for post
Basic yield*

Explanation

function* g2() {
yield 1;
yield 2;
yield 3;
yield 4;
yield 5;
}

Yield* with Return

Image for post
Image for post
Yield* with return

Explanation

Yield* with a Built-in Iterable Object

Image for post
Image for post
Yield over built-in iterables

Best Practices

Image for post
Image for post
Yield with for…of
Image for post
Image for post

Conclusion

DailyJS

JavaScript news and opinion.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app