Member-only story
Yield in JavaScript: Unlocking the Power of Generators
Don’t have Medium Premium. Read it here: simplified.ninja.
Imagine writing JavaScript that can pause mid-execution, hand control back to you, and then resume right where it left off. Sounds like magic? Welcome to the world of yield and generator functions in JavaScript.
Introduction
In the ever-evolving landscape of JavaScript, few features have sparked as much curiosity and potential as the yield
keyword and its companion, generator functions. Introduced with ECMAScript 6 (ES6), these powerful constructs have reshaped how we think about control flow and iterability in JavaScript.
What is Yield?
At its core, yield
is a keyword used exclusively within generator functions. But what exactly does it do?
- Pause and Resume: The
yield
keyword allows a function to pause its execution and return a value to its caller while maintaining its state. It can then resume from where it left off. - Value Production: When a generator function yields a value, it produces it as part of an iteration sequence.
- Two-Way Communication:
yield
sends values out of the generator and can receive values back in when the generator is resumed.