DEV Community

Cover image for Let's Learn Generators in JavaScript πŸš€
Jagroop Singh
Jagroop Singh

Posted on

Let's Learn Generators in JavaScript πŸš€

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! πŸ’»βœ¨

Top comments (23)

Collapse
 
thesohailjafri profile image
Sohail SJ | chakraframer.com

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

Collapse
 
jagroop2001 profile image
Jagroop Singh

You're welcome! @thesohailjafri

Collapse
 
thesohailjafri profile image
Sohail SJ | chakraframer.com

learning new things every day from you, keep it up bro <3

Collapse
 
itamartati profile image
Itamar Tati

What's a real world use case for Generators

Collapse
 
pengeszikra profile image
Peter Vivo

redux-saga is great generator based library extending by redux with async state handling for complex busines logic.

I write a POC program - long time ago, when generator released in JS :
poker game poc, with generators and regexp
The main game loop was solved with generator.

Collapse
 
jagroop2001 profile image
Jagroop Singh

Great example @pengeszikra

Collapse
 
philip_zhang_854092d88473 profile image
Philip

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.

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks for the insightful take!

Collapse
 
slobodan4nista profile image
Slobi

Level up content!

Collapse
 
jagroop2001 profile image
Jagroop Singh

Absolutely! Let's keep pushing boundaries and discovering new possibilities! πŸ’‘πŸš€

Collapse
 
momodev profile image
Santiago G. MarΓ­n

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

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @momodev

Collapse
 
pinwheeler profile image
Anthony Dreessen

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

Collapse
 
jagroop2001 profile image
Jagroop Singh

Thanks @pinwheeler

Collapse
 
gauravsinghbisht profile image
Gaurav Singh Bisht

Great tutorial. It is an awesome feature

Collapse
 
jagroop2001 profile image
Jagroop Singh
Collapse
 
dan_maroff profile image
Dan Maroff

Fantastic! Didn’t know this functionality existed in JavaScript πŸ˜€

Collapse
 
jagroop2001 profile image
Jagroop Singh

That's awesome! JavaScript keeps surprising us with its hidden gems! πŸš€

Collapse
 
starboysharma profile image
Pankaj Sharma

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

Collapse
 
skhmt profile image
Mike • Edited

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

Some comments may only be visible to logged-in visitors. Sign in to view all comments.