Introduction to generators

Generators in Javascript are one of the special class functions that simplify your task of writing iterators. Javascript Generators generate a series of values. Generators can be defined as the normal functions, but they can return (yield) multiple values whereas normal functions can have only one return value.

Yield statement in the generator function will pause the function execution when it is called and it does have the functionality to resume, which will continue its execution from the last yield run.

//sample generator function definition

function* generator() {

yield 1;

yield 2;

yield 3;

}

From the above example, it looks like a normal function definition, but since it is a generator function, it has function* in it, instead of the function keyword. And it uses yield statement instead of the return statement, by which it can yield multiple values from a single function.

Generator Object

Generator functions will return objects when it is called. It can be used by looping the object because it is iterable or we can use the next method in these objects.

let genObj = generator.next();

console.log(genObj);

Output:

{ value: 1, done: false }

When the done becomes true, it means that the generator function is in its last execution, it will no more return values.

So we can get the value by using the generator object,

let genObj = generator();

console.log(genObj.next().value);

console.log(genObj.next().value);

console.log(genObj.next().value);

console.log(genObj.next().value);

Output:

1

2

3

undefined

When the last yield statement returns it’s valued, if it is called again, then it will return the value undefined.

Once the generated value is exhausted, we cannot iterate it again. All we can do is to create a new generator object & then use it.

#javascript #generators

Generators In JavaScript With Examples
1.15 GEEK