Generator Function in Javascript

Generator Function in Javascript

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().

Screen Shot 2022-11-29 at 11.13.14 PM.png

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()

Screen Shot 2022-11-30 at 1.13.20 AM.png

Now, follow this code

function* generate() {
  console.log("1");
  yield 1;
  console.log("2");
  yield 2;
}

let gen = generate();

console.log(gen.next());

Screen Shot 2022-11-30 at 2.15.42 AM.png

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.

Screen Shot 2022-11-30 at 2.19.12 AM.png

Don't confuse it with value. Just look at the bellow code.

Screen Shot 2022-11-30 at 2.26.16 AM.png

Hopefully, you understand why the value of done is true in the last one.

We can access the value using gen.next().value.

Screen Shot 2022-11-30 at 2.28.45 AM.png

Hopefully, now you understand how the generator function works.

Happy Coding !!!