JavaScript Generators: The Complete Guide

A generator appears to be a function but behaves like an iterator. As a result, generators are an entirely new flow of control. It allows you to pause execution at any particular time, which is very lazy but powerful.

Generators in JavaScript

Generators in JavaScript are functions that can stop midway and then continue from where they stopped. Generators are an entirely new flow of control. It allows you to pause execution at any particular time, which is very lazy but powerful.

Generators are also called Pausable Functions. So, a generator function can stop and be restarted as often as you want.

Standard Function

It takes an argument that is not necessary and returns a new value. Functions are a fundamental necessity in the programming language. When we call the functions, it will start execution, and we can not interrupt it until it has been done. So we can not pause during its execution.

//main.js

let fun = hello => console.log(`${hello}, how are you`);
fun('hello');

Output

hello, how are you

If you run the above code directly, you maybe face the following errors.

Possible Errors

  1. You can get any syntax errors.
  2. If you perform code directly in your browser, then chances are very high to fail the webpack compilation process.

Possible Solutions

  1.  Beginner’s Guide To Setup ES6 Development Environment  Follow this article strictly and put the above code in the main.js file.

Generator Functions

Syntax

function *hello(){
   // body
}

Or

function* hello() {
  //body
}

Example #1

//main.js

function* generate() {
   console.log(`hello`);
}
let gen = generate();
console.log(gen);

If you see it in the console panel, nothing will show up. So what happens to the log statement? Well, don’t worry. That is how generators work. It is not working the same as Functions are working. Generators return an Iterator, on which you call the next() method.

If you do not know what an Iterator ischeck out my other article on Iterators in Javascript.

//main.js

function* generate() {
   console.log(`hello`);
}
let gen = generate();
console.log(gen.next());

So, generate() function will return an object you can call the next() method. If you remember Iterator, it will return an object containing two properties.

Object {value: undefined, done: true}

Now, you will understand that Generators are generating an Iterable object, which you can call all the Iterators methods like next().

Our example’s output will be the same as the above snippet.

Output

Object {value: undefined, done: true}

The value property here is undefined. We can provide values using various methods.

//main.js

function* generate() {
    yield 'krunal'
   console.log(`hello`);
}
let gen = generate();
console.log(gen.next().value);

Output

krunal

yield

In generators, communication happens in both directions. First, you can pass the values into the generator function. Then, the next() method can take values to be assigned.

In the above example, we used a keyword called “yield“, what does it mean that we have assigned the value to the generator function. Above example, we have assigned the ‘krunal‘ string value to the generator function. So in output of gen.next(), it will return the object containing the properties like {value: ‘krunal’, done: false}

We can also assign the generator value by passing the arguments to that generator function.

//main.js

function* generate() {
   let result = yield;
   console.log(result);
}
let gen = generate();
gen.next();
gen.next('krunal');

Output

krunal

Example #2

/main.js

function* generate() {
  yield 1;
  yield ['krunal','ankit','rushabh'];
}
let gen = generate();
console.log(gen.next().value);
console.log(gen.next().value);

Output

1
['krunal','ankit','rushabh']

In the above example, we are yielding two values. That is why it will log the value one by one. If we want to iterate the array, we want to do the following.

//main.js

function* generate() {
  yield 10;
  yield* ['krunal','ankit','rushabh'];
}
let gen = generate();
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);
console.log(gen.next().value);

Output

10
krunal
ankit
rushabh

The yield* behaves like an iterator, and we can iterate one by one and log the value in the console.

Example #3

//main.js

function* generate() {
  yield 10;
  yield 20;
  yield 30;
}
let gen = generate();
for(value of gen){
    console.log(value);
}

Here is proof that the generator generates an iterator. We can iterate a for..of loop and log the values on the iterator.

generators in es6
Generators in es6
  1. The generator generates an iterable object, which we can call the next() method, and we can take control over a function.
  2. Generators are pausable and resumable functions as many times as you want.
  3. We can use generators to cancel asynchronous operations quickly.
  4. The generator function syntax is just like a regular function but with an asterisk(*) after the function keyword.
  5. When you call a generator function, it should not execute the function like a regular function but will return an object called an iterator.
  6. We can pass the argument via the next() method and then yield a resume to the generator’s execution.
  7. yield* can also work as an iterator, and we can use the for..of loop over it.

That’s it for Generators in JavaScript.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.