A regular function is executed based on the run-to-completion model. It cannot pause midway and then continues from where it paused. But the generator function can do it. Let's explore it with an example.
//normal function
function normal() {
console.log('I');
console.log('am');
console.log('normal function');
}
normal();
When we call the above function then it printed all contents one after one. It can't take pause.
//generator function
function* generate() {
console.log('1');
yield 1;
console.log('2');
yield 2;
}
The generator function starts with function*
. Now call this function. What is the output?
Wait! Your compiler is working fine. Actually, if you call this function like as a normal function, nothing will happen. Now try this way generate().next()
.
Output is 1. But what happened here? If you remember, I explained earlier generator function can pause the execution. Here yield
paused the execution. This is the reason, that only 1
is printed. yield
is triggered by the next()
. Now call gen.next()
again, then 2
will be printed.
function* generate() {
console.log("1");
yield 1;
console.log("2");
yield 2;
}
let gen = generate();
gen.next()
gen.next()
Now, follow this code
function* generate() {
console.log("1");
yield 1;
console.log("2");
yield 2;
}
let gen = generate();
console.log(gen.next());
The generator function returns two properties. value
and done
. done
is determined whether more yield
exists or not. If yield
exists then the done
value is false
.
Don't confuse it with value
. Just look at the bellow code.
Hopefully, you understand why the value of done
is true
in the last one.
We can access the value
using gen.next().value
.
Hopefully, now you understand how the generator function works.
Happy Coding !!!