Generators
In ES6 we have a new type of function, which is called generator
. A generator is a function that can be paused and resumed, which means that a generator can produce a sequence of values
Creating a generator
To create a generator, we use the function*
syntax:
function* generator() {
yield 1;
yield 2;
yield 3;
}
Here we defined a generator called generator
, that generator contains three yield
statements. A yield
statement is used to pause the generator and return a value.
Using a generator
To use a generator, we call it like a normal function:
const gen = generator();
Then we can use the next()
method to get the next value from the generator:
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
console.log(gen.next()); // { value: undefined, done: true }
As we can see, the next()
method returns an object with two properties, value
and done
. The value
property contains the value that was returned from the generator, and the done
property is a boolean that indicates if the generator has finished or not.
Using a generator with a for...of loop
We can use a generator with a for...of
loop to get all the values from the generator:
for (const value of generator()) {
console.log(value); // 1, 2, 3
}
Using a generator with the spread operator
We can use a generator with the spread
operator to get all the values from the generator:
console.log(...generator()); // 1 2 3
What is the purpose of using generators?
Generators are useful when we want to produce a sequence of values, for example, we can use a generator to produce a sequence of numbers:
function* numbers() {
let i = 0;
while (true) {
yield i++;
}
}
Here we defined a generator called numbers
, that generator contains an infinite loop, and in each iteration we yield the value of i
and then increment it.
Now we can use the numbers
generator to get a sequence of numbers:
const gen = numbers();
console.log(gen.next()); // { value: 0, done: false }
console.log(gen.next()); // { value: 1, done: false }
console.log(gen.next()); // { value: 2, done: false }
console.log(gen.next()); // { value: 3, done: false }
It will keep producing numbers forever.
Real World Example in Javascript
Let's see a real world example of using generators in Javascript. We will use generators to create a range
function, that will produce a sequence of numbers:
function* range(start, end) {
for (let i = start; i <= end; i++) {
yield i;
}
}
Here we defined a generator called range
, that generator contains a for
loop, and in each iteration we yield the value of i
.
Now we can use the range
generator to get a sequence of numbers:
for (const value of range(1, 5)) {
console.log(value); // 1, 2, 3, 4, 5
}
But why not using a normal function?
We can use a normal function to produce a sequence of numbers:
function range(start, end) {
const result = [];
for (let i = start; i <= end; i++) {
result.push(i);
}
return result;
}
Here we defined a function called range
, that function contains a for
loop, and in each iteration we push the value of i
to the result
array.
Now we can use the range
function to get a sequence of numbers:
console.log(range(1, 5)); // [1, 2, 3, 4, 5]
So why not using a normal function instead of a generator? The answer is that generators are lazy, which means that they don't produce all the values at once, they produce the values only when we need them.
Which means that if we have a very large sequence
of numbers, we can use a generator to produce the numbers one by one, instead of producing all the numbers at once.
This will reduce the memory usage, and will make our code more efficient.
🎨 Conclusion
In this article, we talked about generators, and how to use it and why we should use it.
☕♨️ Buy me a Coffee ♨️☕
If you enjoy my articles and see it useful to you, you may buy me a coffee, it will help me to keep going and keep creating more content.
😍 Join our community
Join our community on Discord to get help and support (Node Js 2023 Channel).
📚 Bonus Content 📚
You may have a look at these articles, it will definitely boost your knowledge and productivity.
General Topics
- Event Driven Architecture: A Practical Guide in Javascript
- Best Practices For Case Styles: Camel, Pascal, Snake, and Kebab Case In Node And Javascript
- After 6 years of practicing MongoDB, Here are my thoughts on MongoDB vs MySQL
Packages & Libraries
- Collections: Your ultimate Javascript Arrays Manager
- Supportive Is: an elegant utility to check types of values in JavaScript
- Localization: An agnostic i18n package to manage localization in your project
React Js Packages
Courses (Articles)
Top comments (1)
Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍