Generators


In this post I will attempt to make sense of JavaScript Generators

yield means pause!

declared with a * (example: function *foo(){}

must be assigned to a var (example: var gen = foo();

So here's what a generator looks like

function *foo(x){
 var y = x + (yield 'first pause');
 console.log(y);
}

var gen = foo(6);

gen.next(); // starts the first iteration and spits whatever is in yield
gen.next(1); // replaces whatever was in yield and inputs it

Okay, so what's happening here?  Basically, the yield statement is like a return statement, and but it evaluates whatever comes after it.

Additionally, it's sort of like a two way communication channel.  

First off, an initial next method is called, and yield pauses the iteration of the function. Whatever value is immediately after the yield gets outputted.

Then, the program calls next again, this time with the parameter 1, and replaces the outputted value with the inputted 1, and then evaluates 6 + 1, to get 7.

Then we log the value of y, which is 7!

No Comments