How to use Generators in JavaScript

Generators are a function that can be stopped in mid-way and continued from where it is stopped. In brief, generators are appeared to functions but behave like iterators.

To create a generator, we need to first define a generator function with function* symbol. The objects of generator functions are called generators.

// Generator function Syntax

function* name( ) {

yield statement;

}

We can pause the execution of a generator function without executing the whole function body using the yield keyword.

function * generatorFunction() {

var num = 1;

while( num> 0) {

yield num;

num num + 1;

}

}

var number generatorFunction( );

Console. log(numbers. next());

// {“value” : 1, “done” : false}

console. log(numbers.next());

// {“value” : 1, “done” : false}

We can also use the return statement in a generator function. The return statement returns a value and terminates the function (similar to regular functions)

Uses of Generators

  • Let us write cleaner code while writing asynchronous tasks.
  • Provide an easier way to implement iterators.
  • Execute its code only when required.
  • Memory efficient.

Leave a Reply

Your email address will not be published.