EDUCBA

EDUCBA

MENUMENU
  • Free Tutorials
  • Free Courses
  • Certification Courses
  • 600+ Courses All in One Bundle
  • Login
Home Software Development Software Development Tutorials ES6 Tutorial ES6 Generators
Secondary Sidebar
ES6 Tutorial
  • ES6 Basic and Advance
    • What is ES6
    • ES6 Features
    • ES6 Enum
    • ES6 Array Methods
    • ES6 Spread Operator
    • ES6 Operator
    • ES6 Proxy
    • ES6 New Features
    • ES6 Set
    • ES6 reduce
    • ES6 Destructuring
    • ES6 filter
    • ES6 Cheat Sheet
    • ES6 Template Strings
    • ES6 Generators
    • ES6 Default Parameters
    • ES6 Object Destructuring
    • ES6 Arrow Function
    • ES6 Array
    • ES6 CLASSES
    • ES6 JavaScript
    • ES6 modules

ES6 Generators

ES6 Generators

Definition of ES6 Generators

ES6 generators is a unique function, it can be interrupted in the middle and resumed afterward. When a conventional function is called, control remains with the called function until it returns. However, in ES6, the generator allows the caller function to control the execution of a called function. The new notion introduced in ES6 is the Generator (or Generator function). It enables us to use iterators and functions in a new way. Custom iterators are a great tool, but the requirement to explicitly maintain their internal state necessitates careful programming.

What is ES6 generators?

  • A new type of function called a generator will be one of the most interesting new features in JavaScript ES6. Although the name is unusual, the conduct is much odd.
  • The function* syntax is used to create generator functions. Generator functions are not running their code right away when they are called. Instead, they return a Generator, a specific form of iterator.’
  • The Generator function executes until the yield keyword is encountered when a value is consumed by invoking the generator’s next method.
  • The function can be called as many times as needed, and each time it returns a new Generator. It is possible to repeat each Generator only once.
  • Generators, which debuted in ES6, are a new approach to interact with functions and iterators.
  • A generator is a function that can pause in the middle of its execution and resume from there. In a nutshell, a generator looks like a function but acts as an iterator.
  • Iterators and generators are inextricably connected. The generator function has a syntax that is very similar to that of the ordinary function. The only major distinction is that the generating function is indicated by appending an asterisk (*) to the function term.
  • When a generator function wants to generate a value, it uses the yield keyword instead of the return keyword. When the function is resumed, it resumes where it left off after the last yield run.
  • A generating function returns the Generator object, which follows the iterable and iterator protocols.
  • We can also use it for the loop with the ES6 generator function. Using for loop we can reduce the size of code.

Below syntax shows how to define the function of the generator are as follows.

Start Your Free Software Development Course

Web development, programming languages, Software testing & others

All in One Software Development Bundle(600+ Courses, 50+ projects)
Python TutorialC SharpJavaJavaScript
C Plus PlusSoftware TestingSQLKali Linux
Price
View Courses
600+ Online Courses | 50+ projects | 3000+ Hours | Verifiable Certificates | Lifetime Access
4.6 (86,130 ratings)

Syntax

Function* name_of_function ()
{
Yield 1;
Yield 2;
…..
}
Function* name_of_function1 ()
{
Yield 1;
Yield 2;
…..
}
Function* name_of_function2 ()
{
Yield 1;
Yield 2;
…..
}

Basic ES6 generators

  • We may make a generator throw an exception by invoking its throw () method and supplying the value of the exception we want it to throw.
  • A typical function, cannot be terminated before its task is completed, i.e. before the last line is run. It follows a model known as the run-to-completion model.
  • If we call the function again, it will start from the beginning. A generator, on the other hand, is a function that can pause in the middle and resume from where it left off.
  • Generators are a subset of functions that make writing iterators more straightforward. A generator is a function that generates a succession of values rather than a single value.
  • A generator in JavaScript is a function that returns an object that you may use to call the next method on(). Each time we call next(), we will get a form object.
  • We must manually create an iterator object with the next() method at the time of implementing an iterator. We must also manually save the state.
  • It can be very difficult to accomplish this at times. Generators are iterables, therefore they can be used to implement iterables without the need for additional code.
  • Functions that return a generator object are called generator functions. Calling the generator object’s next method or utilizing the generator object in for loop are two ways to use generator objects.

ES6 generators

  • Generators compute their produced values on demand, allowing them to describe expensive sequences effectively.
  • The generator’s internal state can be modified using the next() method, which receives a value. Yield will receive a value supplied to next().

Below is the example of ES6 generator is as follows.

Example

function* ES6()
{
yield 45;
yield;
yield 90;
}
var generator = ES6();
console.log (generator.next().value);
console.log (generator.next().value);
console.log (generator.next().value);

Output:

1

  • When the function is resumed, it resumes execution immediately after the previous yield run. It has the ability to generate a sequence of values.
  • We utilized the generator’s main method, next(), in the preceding example. When we invoke the next() method with an argument, it resumes the generator function’s execution, substituting the yielded expression where it was interrupted with the argument from the next() method.

In the below example, we have defined function name as gen and also we have defined one yield statement. The below example shows the generator function with yielded value.

function* gen() {
yield 5;
}
var ES6 = gen();
console.log(ES6.next());

  • In the below example, we have defined function name as letter and also we have defined the four yield statements.
  • In the below example, we have used a single letter with each yield statement. We have used letters like A, B, C, D. Also we are using strict keywords with for loop and generator function.

The below example shows the generator function with for loop.

"use strict"
function* letter() {
yield 'A';
yield 'B';
yield 'C';
yield 'D';
}
for(let alpha of letter()) {
console.log (alpha);
}

2

  • The following statement-defined return statements are not executed within a function. As a result, the return statement should be the function’s last statement.
  • In the below example, we have defined function name as gen and also we have defined three yield statements.
  • In the below example, we have defined three yields and one return statement. At the time of calling the next method, the generator function will resume its work till the next statement arrives.

The below example shows the return statement with the generator.

function* gen() {
yield 'First stmt';
yield 'Second stmt';
return 'Return stmt';
yield 'Second stmt';
}
let fun = gen();
console.log (fun.next());
console.log (fun.next());
console.log (fun.next());
console.log (fun.next());

3

Conclusion

Generator functions are not running their code right away when they are called. Instead, they return a Generator, a specific form of iterator. ES6 generators is a unique function in that it can be interrupted in the middle and resumed afterwards.

Recommended Articles

This is a guide to ES6 Generators. Here we discuss the definition, What is ES6 generators? Example and ES6 generators. You may also have a look at the following articles to learn more –

  1. ES6 Features
  2. What is ES6?
  3. ES6 vs ES5
  4. Typescript vs ES6
0 Shares
Share
Tweet
Share
Primary Sidebar
Footer
About Us
  • Blog
  • Who is EDUCBA?
  • Sign Up
  • Live Classes
  • Corporate Training
  • Certificate from Top Institutions
  • Contact Us
  • Verifiable Certificate
  • Reviews
  • Terms and Conditions
  • Privacy Policy
  •  
Apps
  • iPhone & iPad
  • Android
Resources
  • Free Courses
  • Java Tutorials
  • Python Tutorials
  • All Tutorials
Certification Courses
  • All Courses
  • Software Development Course - All in One Bundle
  • Become a Python Developer
  • Java Course
  • Become a Selenium Automation Tester
  • Become an IoT Developer
  • ASP.NET Course
  • VB.NET Course
  • PHP Course

ISO 10004:2018 & ISO 9001:2015 Certified

© 2022 - EDUCBA. ALL RIGHTS RESERVED. THE CERTIFICATION NAMES ARE THE TRADEMARKS OF THEIR RESPECTIVE OWNERS.

EDUCBA
Free Software Development Course

C# Programming, Conditional Constructs, Loops, Arrays, OOPS Concept

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA Login

Forgot Password?

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA
Free Software Development Course

Web development, programming languages, Software testing & others

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

EDUCBA

*Please provide your correct email id. Login details for this Free course will be emailed to you

By signing up, you agree to our Terms of Use and Privacy Policy.

Let’s Get Started

By signing up, you agree to our Terms of Use and Privacy Policy.

This website or its third-party tools use cookies, which are necessary to its functioning and required to achieve the purposes illustrated in the cookie policy. By closing this banner, scrolling this page, clicking a link or continuing to browse otherwise, you agree to our Privacy Policy

Loading . . .
Quiz
Question:

Answer:

Quiz Result
Total QuestionsCorrect AnswersWrong AnswersPercentage

Explore 1000+ varieties of Mock tests View more