Let's Learn Generators in JavaScript 🚀
Jagroop Singh

Jagroop Singh @jagroop2001

About: 👨‍💻 Full Stack Developer | 🤖 Machine Learning Developer | 🤝 Dev Relations Pro – 💼 Available for Hire | 24k+ Followers | 355k+ Views

Location:
India
Joined:
Apr 5, 2022

Let's Learn Generators in JavaScript 🚀

Publish Date: Nov 29 '24
192 27

Hey, JavaScript enthusiasts! 👋 Are you ready to supercharge your coding skills? Today, we’re diving into Generators — a special kind of function in JavaScript. Don’t worry, it’s not rocket science 🚀 (but it’s close)! Let’s cut the jargon and get straight to the action.


What Are Generators? 🤔

In simple terms, Generators are functions that can pause and resume their execution. Unlike regular functions that run from start to finish, generators give you more control.

How? By using the magic of the function* syntax and the yield keyword. Let’s see them in action!


Writing Your First Generator Function 🛠️

function* myFirstGenerator() {
  yield "Hello 🌟";
  yield "Generators are awesome!";
  yield "Goodbye 👋";
}

// Let's use it!
const gen = myFirstGenerator();

console.log(gen.next()); // { value: 'Hello 🌟', done: false }
console.log(gen.next()); // { value: 'Generators are awesome!', done: false }
console.log(gen.next()); // { value: 'Goodbye 👋', done: false }
console.log(gen.next()); // { value: undefined, done: true }
Enter fullscreen mode Exit fullscreen mode

What’s Happening Here?

  1. The yield keyword acts as a pause point in your function.
  2. Each call to gen.next() moves the function to the next yield.
  3. When there are no more yield statements, the generator returns { done: true }.

Practical Use Cases 🎯

1. Infinite Series Generators ♾️

Ever wanted to generate infinite numbers without blowing up your memory? Generators to the rescue!

function* infiniteNumbers() {
  let num = 1;
  while (true) {
    yield num++;
  }
}

const numbers = infiniteNumbers();

console.log(numbers.next().value); // 1
console.log(numbers.next().value); // 2
console.log(numbers.next().value); // 3
// ... and so on
Enter fullscreen mode Exit fullscreen mode

2. Controlled Iteration for Data Fetching 📡

Need to fetch data in chunks or lazy load something? Generators can help:

function* fetchInChunks(data) {
  for (let i = 0; i < data.length; i += 2) {
    yield data.slice(i, i + 2);
  }
}

const chunks = fetchInChunks([1, 2, 3, 4, 5, 6, 7, 8]);

console.log(chunks.next().value); // [1, 2]
console.log(chunks.next().value); // [3, 4]
console.log(chunks.next().value); // [5, 6]
Enter fullscreen mode Exit fullscreen mode

Fun with Delegating Generators 🤹‍♀️

Generators can call other generators using yield*. Let’s make them work together:

function* innerGenerator() {
  yield "I’m the inner generator 🎯";
}

function* outerGenerator() {
  yield "I’m the outer generator 🌟";
  yield* innerGenerator();
  yield "Back to the outer generator 👋";
}

const gen = outerGenerator();

for (const value of gen) {
  console.log(value);
}
Enter fullscreen mode Exit fullscreen mode

Output:

I’m the outer generator 🌟  
I’m the inner generator 🎯  
Back to the outer generator 👋  
Enter fullscreen mode Exit fullscreen mode

Why Use Generators? 🤷‍♂️

  1. Lazy Evaluation: Generate values only when needed.
  2. Better Performance: No need to calculate all results upfront.
  3. Asynchronous Flow: Combine with async/await for cleaner async code.

Trick Question for You! 🤔💡

Can a generator function be asynchronous? If yes, how would you use it?

Drop your answers in the comments or try it out in your code! 🧑‍💻


Wrap-Up 🎉

Generators might seem a bit tricky at first, but with some practice, they can become a powerful tool in your JavaScript arsenal. Start small, explore their possibilities, and soon you'll be wielding them like a pro! 💪

Do you have a cool use case for generators? Share it with us in the comments below! Let’s learn together. 🙌

Happy coding! 💻✨

Comments 27 total

  • Sohail SJ | TheZenLabs
    Sohail SJ | TheZenLabsNov 29, 2024

    Damn, these are so powerful, I can think of n number of ways to use this like a progress bar and infinite scroll block with dynamic data fetching. thanks @jagroop2001

  • Dan Maroff
    Dan MaroffNov 29, 2024

    Fantastic! Didn’t know this functionality existed in JavaScript 😀

    • Jagroop Singh
      Jagroop SinghNov 30, 2024

      That's awesome! JavaScript keeps surprising us with its hidden gems! 🚀

  • Philip
    Philip Nov 29, 2024

    This is an excellent and engaging introduction to JavaScript Generators! 🚀 Generators are powerful for tasks like lazy evaluation and asynchronous flow, and with EchoAPI, you can efficiently test and mock APIs that use generator functions, simplifying your development and debugging process.

  • Slobi
    SlobiNov 29, 2024

    Level up content!

    • Jagroop Singh
      Jagroop SinghNov 30, 2024

      Absolutely! Let's keep pushing boundaries and discovering new possibilities! 💡🚀

  • Itamar Tati
    Itamar Tati Nov 29, 2024

    What's a real world use case for Generators

  • JosefJarman
    JosefJarmanNov 30, 2024

    Here’s a comment for "Let's Learn Generators in JavaScript":

    // This tutorial introduces JavaScript generators, a powerful feature for handling asynchronous operations and managing state. 
    // Generators allow you to pause and resume functions at any point, making them [ideal](https://kukasoittii.fi/) for tasks like lazy evaluation and complex iteration. 
    // The 'function*' syntax and the 'yield' keyword are key to creating generator functions. 
    // Understanding generators helps improve code efficiency and readability when working with asynchronous programming.
    
    Enter fullscreen mode Exit fullscreen mode
    • Jagroop Singh
      Jagroop SinghNov 30, 2024

      What ?

      • Charles Robertson
        Charles RobertsonDec 2, 2024

        What’s even weirder, is that three people have liked that comment?
        I reckon this was Bot generated? Maybe the Likes were, as well?

  • Gaurav Singh Bisht
    Gaurav Singh BishtDec 1, 2024

    Great tutorial. It is an awesome feature

  • netflix app
    netflix appDec 1, 2024

    Netflix MOD APKs are modified versions of the official Netflix app, often claiming to provide premium features for free.

  • Anthony Dreessen
    Anthony DreessenDec 1, 2024

    I forgot I was scared of the yield sign. You completely clarified things. You should be proud of you. I'm proud of you!

  • Santiago "Momo" Marín
    Santiago "Momo" MarínDec 2, 2024

    Great article. First time I've seen actually useful examples for generators. Thanks!

  • Pankaj Sharma
    Pankaj SharmaDec 2, 2024

    So easy to understand and I like the idea of using generators for lazy load data in chunks.

  • Noah Jones
    Noah JonesDec 2, 2024

    Best Programming Codes to Sell ( 🎉 December Special: Get 100% Off! 🎉)

    🚀 Ready to unlock the world of programming? 🌍 Whether you're a beginner or looking to sharpen your skills, our platform offers the perfect place to start! 💻✨

    🔧 Learn the most popular programming languages like Python, JavaScript, HTML/CSS, and more! 📚🔍 With easy-to-follow tutorials, interactive exercises, and real-world projects, you'll be coding like a pro in no time! 🌟👨‍💻👩‍💻

    🔥 Don't wait to build your future in tech! Start your coding journey today and join a community of passionate learners! 🌱💡

    👉 Start learning here - tinyurl.com/cbn583tu

    turn your ideas into reality! 🚀

  • Mike 🐈‍⬛
    Mike 🐈‍⬛Dec 3, 2024

    To be fair it's closer to a 1.7976931348623157e+308 series number generator than infinity, although any more than that JS will just return Infinity so maybe it is an infinite number generator

  • Marketing SEO Directory
    Marketing SEO DirectoryDec 3, 2024

    Nice!

  • Berkan Serbes
    Berkan SerbesDec 16, 2024

    Well explained 👍

Add comment