{

Es6 Generator Functions Yield in javascript | Typescript


In this blog post, We are going to learn Generator Functions and Yield keywords with examples. First We will see how Normal Function works? Normal Functions are called, executes it and the function returns finally either return the value of function body execution is completed. Function Example here is a function example, When the function Method is called, a Sequence of statements in a body is executed, finally returned value, and iteration is stopped in its control.

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

method();

Generator Function Introduction

The generator is a special kind of Function that was introduced in ES6- ES2015. These functions control how we want to iterate behavior. when The function is called, It can be paused and resumed. Example Here is an example of Generator Functions

function* generateFunctions() {
    console.log('Generateor Function started');
    yield 'pause';
    console.log('Generateor 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 }

We will see the difference between Normal Function and Generator Function

  • This function starts with function* and normal function starts with function
  • Function execution paused using yield keyword when the below statement executes, the function is not called, It gets the generator function object.
const gfunctions=generateFunctions();

Initially, Function is not called and suspended, You have to call gfunctions.next() to call function body. next() method returns an object which contains the value and done keys. Each time when you called next() method, the function resumes its execution and returns an object which contains and value and done keys value: It is the output of yield code execution done:- status of the execution, false means function execution is not completed

Typescript Function Generator

When you generator function in typescript, It does not work default and gives the following error TS2339: Property ‘next’ does not exist on type You have to make configuration changes to tsconfig.json file and fix for the above error is

"target": "es6",
"lib": [
    "es6"
]

Typescript Yield keyword Typescript supports generator functions and behavior works as expected.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.