AppDividend
Latest Code Tutorials

Generators in ES6 | Javascript Generators Example

0

Generators in ES6 are functions that can stop midway and then continue from where it stopped. In short, a generator appears to be a function but it behaves like an iterator. Generators are the entirely new flow of control. It allows you to pause execution at any particular time, so it is very lazy but very powerful.

Generators in ES6

Generators are the entirely new flow of control. It allows you to pause execution at any particular time, so it is very lazy but very powerful. Generators are also called Pausable Functions. So, a generator function can stop and be restarted, as many times as you want.

Standard Function

It takes an argument or not necessary and return 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 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 in the console panel, nothing will show up. So what happens to 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 next() method.

If you do not know, what is an Iterator, check 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 on which you can call next() method. If you remember Iterator then, it will return an object containing two properties.

Object {value: undefined, done: true}

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

Here in our example, the 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. You can pass the values into the generator function. The next() the method can take values to be assigned.

In the above example, we used a keyword called “yield“, what does it’s mean that we have assigned the value to the generator function. Above example, we have assigned ‘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 via 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. Now, if we want to iterate the array, then 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. On iterator, we can iterate a for..of loop and log the values one by one.

generators in es6
Generators in es6
  1. The generator generates an iterable object on 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 quickly cancel asynchronous operations.
  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 normal function but, it will return an object called an iterator.
  6. We can pass the argument via the next() method and then yield a resume to the execution of a generator.
  7. yield* can also work as an iterator, and we can use the for..of loop over it.
If you still have doubts then ask in the comment below, I am happy to help you out.

Leave A Reply

Your email address will not be published.

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