Generators in JavaScript Explained
Michael Mitrakos
5 min read
Having worked across sites raking in over 50 billion website visits annually with Higglo Digital I write about tech topics and teach engineers to have solid foundations that will help them get ahead in their career. I also build awesome products for digital nomads — check it out!
JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. Check out the ebook now!
Generators are a feature in JavaScript that allow developers to create iterators with a special syntax. They are a type of function that can be paused and resumed, allowing developers to create custom iterators that can yield multiple values over time.
To create a generator function, you use the function* syntax and include a yield keyword within the function body. The yield keyword is used to pause the generator function and return a value to the calling code. Here is an example of a simple generator function:
function* generator() {
yield 1;
yield 2;
yield 3;
}To use a generator function, you must call it and store the returned generator object in a variable. You can then iterate over the generator object using a loop or the next() method. Here is an example of iterating over a generator object using a for...of loop:
console.log(value);
}
// Output: 1 2 3In this example, the generator object is iterated over using a for...of loop, which automatically calls the generator's next() method on each iteration. The generator function is paused at each yield keyword, and the value of the yield
You can also manually iterate over a generator object using the next() method, which returns an object with a value property and a done property. The value property contains the value returned by the generator function, and the done property is a boolean that indicates whether the generator has completed its execution. Here is an example of manually iterating over a generator object using the next() method:
result = generator.next();
}
// Output: 1 2 3In this example, the generator’s next() method is called in a loop until the done property of the returned object is true
Generators can also accept arguments and return values, just like regular functions. To pass an argument to a generator function, you use the next() method and pass the argument as an argument to the method. The generator function is then resumed with the passed argument as the value of the yield expression. Here is an example of a generator function that accepts an argument:
function* generator(num) {
return result;
}
console.log(result.value); // Output: undefined
result = generator.next(10);
console.log(result.value); // Output: 10In this example, the generator function accepts an argument num and yields it multiplied by 2. The generator function is then paused and the calling code calls the generator's next() method with an argument of 10. This argument is passed as the value of the yield expression when the generator function is resumed, and the generator function returns the passed argument as the result.
Generators can be a useful tool for creating custom iterators in JavaScript, and they offer a flexible and powerful syntax for creating iterators that can yield multiple values over time. They can be especially useful for working with asynchronous code, as they allow developers to create iterators that can pause and resume their execution, allowing other code to run in the meantime.
Here is an example of using a generator function to perform an asynchronous task:
function* getData() {
const data = yield response.json();
return data;
}
async function main() {
let response = await result.value;
result = generator.next(response);
let data = await result.value;
console.log(data);
}Generators can be a powerful tool for working with arrays and asynchronous code in JavaScript, and they offer a unique syntax for creating custom iterators. It is important to understand how generators work and how to use them effectively in order to write efficient and effective code.
JavaScript eBook
I’ve written an eBook on JavaScript that will take you from beginner to professional. Having been in your shoes moving to making over $200,000 per year in just a few years as a software engineer, I know exactly what it takes to get there. Check out the ebook now!
I founded Higglo Digital and we can help your business crush the web game with an award-winning website and cutting-edge digital strategy. If you want to see a beautifully designed website, check us out.
I also created Wanderlust Extension to discover the most beautiful places across the world with highly curated content. Check it out!
Related reading
Master Recursion in JavaScript: Tips, Tricks, and Examples
Diving into the world of JavaScript, we often encounter concepts that seem daunting at first glance. Recursion is one such concept, a powerful tool that, when…
JavaScript Promises Explained for Beginners: Master Async Code
If you’ve ever found yourself scratching your head over asynchronous operations in JavaScript, you’re not alone. It’s a common hurdle for beginners, but that’s…
Beginner’s Guide to JavaScript Cross-Browser Compatibility
Ever found yourself scratching your head wondering why your JavaScript code works like a charm in Chrome but throws a tantrum in Internet Explorer? Welcome to…