Generators in ES6

Hello, web artisans, In today’s AppDividend Tutorial, I have briefly described Generators in ES6.

Generators

Generators are the entirely new flow of control. It allows you to pause of 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 directly run above code in the browser, then you might face the following issue.

Possible Errors

  1. You can get any syntax error.
  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 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, the nothing will show up. So what happens to log statement. Well, don’t worry. That is how generators work. It is not working 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 another 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.

Read More
1 of 2
Object {value: undefined, done: true}

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

Here in our example, the output will be the same as above snippet.

Output

Object {value: undefined, done: true}

Value property here is undefined. We can provide the 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 the 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 its 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 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 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

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 the proof that 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

Memorable Points

  1. The generator generates an iterable object on which we can call the next() method, and we can take the 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 next() method and then yield resume 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 doubt then ask in the comment below, I am happy to help you out.

You might also like More from author

Leave A Reply

Your email address will not be published.