Introduction and use of Javascript generator

Introduction and use of Javascript generator

What is a generator?

A generator is some code that runs inside a function.

  • After returning the value, it will pause itself and -
  • The caller can ask to cancel the pause and return another value

This "return" is not a traditional return from a function. So it is given a special name - yield.

Generator syntax varies from language to language. Javascript's generator syntax is similar to PHP's, but it's different enough that if you expect them to work the same, you'll end up being very confused.

In javascript, if you want to use a generator, you need to:

  • Defining special generator functions
  • Call this function to create a generator object
  • Use the generator object in a loop or call its next method directly.

We start with this simple program and follow each of the steps below:

// File: sample-program.js
function *createGenerator() {
 for(let i=0;i<20;i++) {
 yield i
 }
}

const generator = createGenerator()

console.log(generator.next())
console.log(generator.next())

If you run this code, you will get the following output:

$ node sample-program.js

{ value: 0, done: false }
{ value: 1, done: false }

Let me explain how the program works.

Generator Functions

First, there is the definition of the generator function in the code:

function* createGenerator() {
 for(let i=0;i<20;i++) {
 yield i
 }
}

The * after function tells JavaScript that this is a generator function. The following are all valid definitions of generator functions.

function*createGenerator
function* createGenerator
function *createGenerator

The * is not part of the function name. Instead, the function* notation defines a generator.

Calling the generator function

After defining the generator function, we call it a function of some other name.

// NOTE: When called, there is no *. * is not part of the function name // `function *` is the symbol used to define a generator function const generator = createGenerator()

But remember: the createGenerator function has no return value. This is because generator functions don't have a traditional return value. In contrast, when you call a generator function directly, it always returns an instantiated Generator object.

This generator object has a next method. Calling next will run the code inside the generator function.

function* createGenerator() {
 for(let i=0;i<20;i++) {
  yield i
 }
}

This is important enough to call it again. Calling a generator function directly does not run any code in the generator function. Instead, a generator object is created. It calls next on the generator object, which in turn calls the code in the generator function.

The first time next is called on a generator object, the code inside runs until a yield statement is encountered. Once a yield is reached, javascript will pause execution of that code, and next will return (give you, or yield) an object containing the value in the yield line.

When you call next a second time (or third, fourth, or more times), the code will be unpaused and continue running (where it left off on the last call). The variable (i in this case) will retain its value. When the code reaches another yield statement, the function pauses again and returns an object containing the yielded value.

That's why we call next twice.

console.log(generator.next())
console.log(generator.next())

You will get the following output:

{ value: 0, done: false }
{ value: 1, done: false }

Once the code in the generator function has finished executing, any future calls to next will return an object with a value of undefined and done set to true.

{ value: undefined, done: true }

Generators and loops

Although it is possible to call next manually on a generator object, we mainly want to use it in a loop. Take a look at this slightly modified program.

// File: sample-program.js
@highlightsyntax@jscript
function *createGenerator() {
 for(let i=0;i<5;i++) {
 yield i
 }
}

const generator = createGenerator()
for(const value of generator) {
 console.log(value)
}

When a generator object is used in a for...of loop, each time through the loop next is called on the generator object and the variable (value above) is filled with the produced value. Running the program will output the following:

$ node sample-program.js
0
1
2
3
4

In the next article, we'll take a closer look at the for ... of loop and explore how JavaScript has a built-in way to loop over any object in JavaScript.

Summarize

This is the end of this article about Javascript Generator. For more relevant Javascript Generator content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • Detailed explanation of Generators in JavaScript ES6
  • Why JS says async/await is the syntax sugar of generator
  • In-depth explanation of the Generator function in js
  • js uses generator function to synchronously execute ajax tasks
  • How to use Generator in JavaScript
  • In-depth understanding of js generator data types
  • Detailed explanation of ES6 generator data type in JavaScript
  • A brief discussion on the use of Generator and Iterator in JavaScript
  • A brief analysis of JavaScript arrow function generator Date JSON
  • Using Javascript Generators in Node.js

<<:  Friendly Alternatives to Find Tool in Linux

>>:  Detailed explanation of performance monitoring of MySQL server using Prometheus and Grafana

Recommend

Three Ways to Find the Longest Word in a String in JavaScript (Recommended)

This article is based on the Free Code Camp Basic...

Some wonderful uses of URL objects in JavaScript

Table of contents Preface Parsing parameters Modi...

How to set up a deployment project under Linux system

1. Modify the firewall settings and open the corr...

Solve the cross-domain problem of Vue+SpringBoot+Shiro

Table of contents 1. Configure Vue front end 1. D...

Common usage of regular expressions in Mysql

Common usage of Regexp in Mysql Fuzzy matching, c...

Similar to HTML tags: strong and em, q, cite, blockquote

There are some tags in XHTML that have similar fu...

Detailed tutorial on installing Python 3 virtual environment in Ubuntu 20.04

The following are all performed on my virtual mac...

How to use JS to check if an element is within the viewport

Preface Share two methods to monitor whether an e...

Vue.js implements music player

This article shares the specific code of Vue.js t...

JavaScript implements double-ended queue

This article example shares the specific code of ...

How to build a MySQL PXC cluster

Table of contents 1. Introduction to PXC 1.1 Intr...

XHTML Web Page Tutorial

<br />This article is mainly to let beginner...

How to correctly create MySQL indexes

Indexing is similar to building bibliographic ind...