Member-only story
Advanced Guide to yield
vs yield*
in JavaScript
In JavaScript, yield
and yield*
are two powerful features of generators, introduced in ES6 (ECMAScript 2015). Generators allow you to pause and resume the execution of functions, making them highly useful for asynchronous programming, handling infinite sequences, or building iterators. While yield
pauses the generator and returns a value, yield*
allows you to delegate to another generator or iterable.
In this guide, we’ll explore the differences, nuances, and advanced use cases of yield
vs. yield*
, helping you better understand how to work with these features effectively in modern JavaScript.
1. What is a Generator?
Before diving into yield
and yield*
, let's review generators. A generator function is defined using the function*
syntax and returns a generator object when called. A generator object allows you to pause and resume execution using the yield
keyword.
Basic Generator Example
function* simpleGenerator() {
yield 1;
yield 2;
yield 3;
}
const gen = simpleGenerator();console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // {…