Generator in ES6 | ECMAScript 6

ECMAScript 6 recommends a new way of working with iterators and functions. The way is named as generator or generator function. The ES 6 generator is a distinct type of function that is used to stop in the midway for one or more than one time and can be resumed later. In other words, we can say that the ECMAScript 6 generator looks like a function but behaves like an iterator.

When a normal function is called, the control rests with the called function until it returns. In the ECMAScript 6 generators, the caller function always has control over the execution of the called function.

The generator can also be defined as-

“The Generator is a function class used to classify the objective of iterator writing.

“The Generator is also used as a function that generates results in a sequence rather than a single value.”

The Generator function is almost similar to regular or normal function except the following points-

  • Generator function yields or returns control back to the caller function at any point.
  • When we call the generator function, it does not run the code; instead it returns an object. It manages the execution.

Syntax

function * function1_ name ()
 {
       yield ‘Hello ES 6’;                     // statement 
        yield ‘Hello generator’;           // statement
 }                    
 var f1 = function1_ name ()                                // Generator function calling
 console.log (f1.next().value); 
  console.log (f1.next().value); 

Example

function* function ()                                    // The generator function
 {
         yield ‘Welcome to generator function’;
        yield ‘Welcome to JavaScript’;
        yield ‘Hello ECMAScript’;  
 }
 var genfunction = function ();                                      // Generator function calling 
 console.log (genfunction.next().value);
 console.log (genfunction.next().value);
 console.log (genfunction.next().value); 

Output

After the execution of the code, we will get the following output.

Generator in ECMAScript 6

The Yield Statement

The Yield statement is used to pause and resume the generator function asynchronously. The yield suspends the function and returns a value to the caller function. It can generate a sequence of values.

The yield statement retains enough state to enable the function to resume where we stopped it before. When we resume the function, it will start to continue its execution after the last yield function ran.

Next Method ()

The Next method () is the essential method of the generator function. When we are going to call the next method () containing its arguments, it will start the execution of the generator function, changing the yield expression where the execution was stopped with argument from the next method.

The next method () return us the object that contains the following two properties-

Done: Done is a Boolean value; returns true if the function code is completed; otherwise it returns false.

Value: It can be the yield value.

We can better understand it with the help of the following instance.

Example

function * display ()
 {
         Yield 500;
 }
 var gen1 = display ();              // gen1 is the generator object 
 console.log (gen1.next()); 

Output

After the execution of the code, we will get the following output.

Generator in ECMAScript 6

 The Return statement in Generator object

The essential work of return statement is to send a particular value back to its caller function. It is used to perform the execution and generate result for the caller. The return statement should be the last statement of the function because the statement defined after the return statement are not executed in the function.

Here, we have an example to illustrate the return statement in a generator.

Example

function* gen1 ()
 {
           yield ‘Hello ECMAScript 6’;
 yield ‘Hello JavaScript’;
 return ‘Return statement’;
 yield ‘Hello Java’;
 yield ‘Hello ECMAScript 6’; 
 }  
 let genobject = gen1 ();
 console.log (genobject.next ());
 console.log (genobject.next ());
 console.log (genobject.next ());
 console.log (genobject.next ());
 console.log (genobject.next ()); 

Output

After the execution of the above example, we will get the following output.

Generator in ECMAScript 6

In the above example code, we have a function gen1 () which contains five statements, including yield and return statements. If we call the next () method, thenthe function resumes until it starts the execution of next yield.    

In the code, when we called the first next () method, returns ‘hello ES 6.’ When we called the second next () method, returns ‘hello JavaScript.’ When we called the next () method, the function returns other remaining value of yield statements. Still when we called the last yield statement, it returns the undefine statement because these statements are written after the return statement.

Generator Object

The generator function returns the generator objects. The Generator object is also defined as an instance of the generator function. It allows the iterator and iterator interface.

We can use these generator objects either by calling the next () method or with the help of generator objects inside a loop.It is an iterator, so we can use it in functions and for…of loop. 

Generator function in for…of loop

The for…of loop with the generator function helps us to make the code short and precise. It also helps us to reduce the line of code.

We can understand it with the help of the following example.

Example

“use strict”
 function* name ()
 {
           }  
 for (let value of name ());
 {
          console.log (name);
 } 

Output

After the execution of the code, we will get the following output.

Generator in ECMAScript 6

Difference between Regular/normal function and Generator function

           Regular Function            Generator Function
It starts with function (). It starts with function*.
It can only return for one time. It can yield (return) many numbers of times.
It uses the return keyword. It uses the yield keyword.
Syntax               function function_name ()         {                   // statement to be executed         } Syntax              Function* function_name ()      {                 yield statement;      }
Generator in ECMAScript 6

Related Topics

Types of Inheritance in ES6

Types of Inheritance The term inheritance can be divided into following three parts- Single-level InheritanceMultiple InheritanceMulti-level Inheritance Single-level Inheritance The single-level inheritance can be defined as an inheritance in which the child class can...

5 minutes read.

Loop Control Statement in ES6

Loop Control Statement in ECMAScript 6 The loop control statements can be defined as a set of conditions that control the execution of the loop. It executes the loop until the condition becomes false....

6 minutes read.

Number in ES6

Number in ES6 In ES6, we have various methods and properties to implement numeric functions such as floating-point, integers, date, etc. The numbers in ES6 enable us to work with number...

7 minutes read.

Features of ES6 | ECMAScript 6

The ES6 or ECMAScript 2015 came with various exiting and new features. These features make it a more robust and updated programming language than ES5. Some of these new promising features are Const...

6 minutes read.

Class in ES6

Class in ES6: The Class is a basic term in object-oriented programming (OOPs). A class helps to determine the prototype for modeling in real-world objects. It is used to formulate...

4 minutes read.

Generator in ES6 | ECMAScript 6

ECMAScript 6 recommends a new way of working with iterators and functions. The way is named as generator or generator function. The ES 6 generator is a distinct type of function that...

5 minutes read.

Dialog box in ES6

Dialog box in ES6 A dialog box can be defined as a regular type of window in the Graphical User Interface (GUI) of the operating system. It is also spelled as...

5 minutes read.

Arrow Function in ES6

Arrow Function in ES6  An Arrow function is a new concept recommended in ECMAScript 2015. It is also called “Fat Arrow Function.” It helps us to write the function more accurately. This function...

5 minutes read.

Object in ES6

Object in ES6 The term object can be defined as an instance that contains the group of key-value pairs. We can modify it using the life cycle of an object in...

6 minutes read.

Object Destructuring in ES6

Object Destructuring in ES6 The term destructuring is referred to as the breakdown of the complex entities into simpler parts. It works like array destructuring. In the array destructuring, the values...

3 minutes read.

Void Keyword in ES6

Void Keyword in ES6 In ES6, the void keyword is referred to as a function return type, but it does not return any value. It classifies the expression and returns the...

2 minutes read.

String in ES6

String in ES6 The term string can be defined as an object used to represent the sequence of the characters. The string is widely used to store a text-based value like...

9 minutes read.

Boolean in ES6

Boolean in ES6 In ES6, the Boolean object is used to show two values either it may be true or false. In JavaScript, we can use the Boolean object as a...

4 minutes read.

Functions in ES6 | ECMAScript 6

Functions in ECMAScript 6 In ECMAScript programming language, the term ‘function’ can be defined as a collection or group of input statements, used to perform particular computational calculations and generate the output...

9 minutes read.

Array Destructuring in ES6

Array Destructuring in ES6 The term ‘Destructuring’ is defined as dividing the complicated data structure into easier modules. The Destructuring syntax helps to extract the small segments from an array and the objects....

3 minutes read.

Loops in ES6 | ECMAScript 6

Loops in ECMAScript 6 A Loop statement can be defined as a group of instructions that are always repeated. In the computer programming language, the loops help us to execute a collection of instructions...

8 minutes read.

Environment Set up in ES6

Environment Set up in ES6 JavaScript is a portable language. It can execute on any browser or any host, and any operating system. Before the use of JavaScript, we need to...

5 minutes read.

Cookies in ES6

Cookies in ES6 The cookies are an old client-side storage technique produced in a server-side scripting language such as Php and ASP etc. The cookie can be defined as a small...

6 minutes read.

Decision-Making in ES6 | ECMAScript 6

Decision-Making in ECMAScript 6 The Decision-making structure or statements are used to determine one or more than one condition to be evaluated or tested. The Decision-making statement helps us to decide...

7 minutes read.

ES6 Tutorial

Introduction of ES6 The ECMAScript 6 is a scripting language specification institutionalized by ECMA International. ECMA, named in 1994, is an international organization, related to information and communication system. ECMA stands for “European Computer Manufacturers...

8 minutes read.