JS Generator
Written By: Avinash Malhotra
Updated on
Generator
JS Generators or Generator Functions are functions that that can be paused and resumed. Generator Functions are helpful in iterators and asynchronous programming.
A function return only one, but Generator can return or yield multiple values one by one, thus can be used as iterators.
Generator Functions starts with function* and then name of function. Generators are paused in middle via yield.
function* generator(){
yield 1;
yield 2;
}
let gen=generator();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
Generator Function
Generator Function are created using function*
followed by name of generator function. Unlike regular functions which returns a value, generator function returns a object called called generator object.
generator {<suspended>}
function* generator(){
yield 1;
yield 2;
}
let gen=generator();
console.log(gen);
Properties of Generator Object
Generator Object can have properties like
- next
- return
- throw
yield
yield is used to return multiple values from generator function. To get the value of yield, we need to use next()
method of generator object.
next() can be used every time to get the value of yield.
The value of next() is an object with two properties,
- value: value of yield
- done: boolean, false for yield, true for return
{value:1; done:false}
{value:2; done:false}
function* generator(){
yield 1;
yield 2;
}
let gen=generator();
console.log(gen.next());
console.log(gen.next());
return in generator
{value:1; done:false}
{value:2; done:false}
{value:3; done:true}
function* generator(){
yield 1;
yield 2;
return 3
}
let gen=generator();
console.log(gen.next());
console.log(gen.next());
console.log(gen.next());
iterate
Generator are iterable. This means we can use for of loop to iterate over. Also we don't need to use next() to get yield value.
for..in loop will only iterate yield value, not return.
1
2
function* generator(){
yield 1;
yield 2;
return 3
}
let gen=generator();
for( let i of gen){
console.log(i);
}