JavaScript Generators: Pause and Resume Execution

The only JavaScript function that comes with a "Pause" button. ⏯️ In JavaScript, the golden rule of functions is usually "Run-to-Completion." Once a function starts, it doesn't stop until it returns or finishes. 𝐄𝐧𝐭𝐞𝐫 𝐭𝐡𝐞 𝐆𝐞𝐧𝐞𝐫𝐚𝐭𝐨𝐫 𝐅𝐮𝐧𝐜𝐭𝐢𝐨𝐧. 🤯 It completely breaks the rule. It is a special type of function that can be paused in the middle of execution and resumed later from exactly where it left off. 𝐓𝐡𝐞 𝐌𝐚𝐠𝐢𝐜 𝐒𝐲𝐧𝐭𝐚𝐱: 1️⃣ `function*`: The asterisk tells JS this isn't a normal function. 2️⃣ `yield`: This keyword acts like a pause button. It spits out a value and freezes the function's state. 3️⃣ `.next()`: This is the play button. Call it to resume the function until it hits the next `yield`. 𝐖𝐡𝐲 𝐢𝐬 𝐭𝐡𝐢𝐬 𝐮𝐬𝐞𝐟𝐮𝐥? (𝐋𝐚𝐳𝐲 𝐄𝐯𝐚𝐥𝐮𝐚𝐭𝐢𝐨𝐧) Generators allow for 𝐋𝐚𝐳𝐲 𝐄𝐯𝐚𝐥𝐮𝐚𝐭𝐢𝐨𝐧. You don't have to calculate a list of 1 million items at once (crashing your memory). You can generate them one by one, only when you actually need them. It’s perfect for infinite streams, ID generators, or defining complex state machines. Check out the syntax breakdown below! 👇 Have you used Generators in production (maybe with Redux Saga)? #JavaScript #WebDevelopment #CodingPatterns #AdvancedJS #SoftwareEngineering #Frontend

  • graphical user interface

To view or add a comment, sign in

Explore content categories