Es6 Generator Functions Yield in javascript | Typescript

In this blog post, we will learn about Generator Functions and the Yield keyword with examples.

First, let’s understand how Normal Functions work. Normal Functions are called, execute, and finally return a value when the function body execution is completed. Here’s an example:

function method() {
  // body
  return value;
}

method();

Introduction to Generator Functions

Generators are a special kind of function introduced in ES6-ES2015. These functions control iteration behavior. When the function is called, it can be paused and resumed.

Here’s an example of Generator Functions:

function* generateFunctions() {
  console.log("Generator Function started");
  yield "pause";
  console.log("Generator Function Completed");
}
const gfunctions = generateFunctions();
console.log(gfunctions.next());
console.log(gfunctions.next());
console.log(gfunctions.next());

Output is

[object Generator]
"Generateor Function started"
Object { value: "pause", done: false }
"Generateor Function Completed"
Object { value: undefined, done: true }
Object { value: undefined, done: true }

Now, let’s explore the difference between Normal Functions and Generator Functions:

  • Generator functions start with function*, whereas normal functions start with function.
  • Function execution is paused using the yield keyword. When the statement below executes, the function is not called; it gets the generator function object.
const gfunctions = generateFunctions();

Initially, the function is not called and suspended. You have to call gfunctions.next() to execute the function body. The next() method returns an object containing the value and done keys. Each time you call the next() method, the function resumes its execution and returns an object containing value and done keys.

  • value: It is the output of the yield code execution.
  • done: It indicates the status of the execution. false means the function execution is not completed.

Typescript Function Generator

When you use a generator function in Typescript, it does not work by default and gives the following error: TS2339: Property ‘next’ does not exist on type.

You have to make configuration changes to the tsconfig.json file to fix this error:

"target": "es6",
"lib": [
    "es6"
]
  • Typescript Yield keyword Typescript supports generator functions, and the behavior works as expected.