One of the coolest features of javascript which surprisingly not many developers know about or use is generator functions. In this tutorial I'll try to explain the generator functions in simple terms and with the help of examples.
A generator function, in short, is a function whose execution can be paused and resumed!
Notice that in other functions we don't have such a control over the execution of the function. This is different from conditional statements and loops where you just control the flow of the execution not the execution itself.
Before diving deeper, let's see an example. Assume we want to have a function to return sequential numbers each time we call it. This is we do it normally:
let id = 0;
function getId() {
return id++;
}
console.log(getId()) // 0
console.log(getId()) // 1
console.log(getId()) // 2
As you can see, actually to write such a function we have to use an external storage to keep the state of our function, a global variable id
in this case. Obviously, now we have to take care of the global variable ourselves and the function doesn't have full control over it.
Now let's see how we do this with a generator function:
function* generateId(id = 0) {
while (true) {
yield id++;
}
}
const ids = generateId();
console.log(ids.next().value) // 0
console.log(ids.next().value) // 1
console.log(ids.next().value) // 2
Ok, this looks crazy! I agree, and this is what I initially thought as well when I saw the syntax for the first time. But there is nothing we cannot break down!
function*
means the function is a generator function, not bad huh?
Then we have yield
, which you can be thought of as a generator-based version of the return
keyword. The main difference is that yield
pauses the execution of the function unlike return
that ends the execution.
I said pause and that's what I exactly meant. In our weird function we have an infinite loop, and here is where the magic of generator functions happen. Each time the generator function returns a value using the yield
statement its execution gets paused until the next call through the iterator
it has returned.
I mentioned iterator
, but to be specific a generator function returns a generator
which is an iterator
on its own. That's why we access the values using the next
method of the generator object (ids
in our example).
Let's keep it short and simple. If you liked this post and want to know more about generator functions
, yield
, generators
comment down bellow and I'll be more than happy to write about it.
Also please not forget to check https://www.utopiops.com for hosting your applications for free. We're in our public beta and will love to collaborate with our users in any possible way. Happy coding!