Skip to main content

Command Palette

Search for a command to run...

Generator Functions in JavaScript: A Simple Guide

Updated
2 min read
Generator Functions in JavaScript: A Simple Guide

Photo by Pankaj Patel on Unsplash

General JavaScript functions can’t be interrupted in the middle of function execution, that is, there is no interruption from the time the function is invoked until function execution completes. When we want to execute functions which can be interrupted or which can execute after a while once execution starts, then we can use a new type of function called generator functions which came into place with ES6.

Fun fact: Async Await is built on top of generator functions

Declaring a generator function:

function* generate() {}

The yield keyword introduced in ES6 is used to stop the execution inside the generator function. It can be used only inside the generator functions and can’t be used inside the general JavaScript functions.

A generator function will always return the iterator object, when the iterator calls a next() method, then the function starts execution till the 1st yield statement. The next() returns an object with two properties:

1. value (any): The value returned by the function till the first yield statement.

2. Done (boolean value): Returns a boolean value true or false which defines whether the function execution is completed or not.

Whenever we use the return statement in the middle of generator functions, it indicates the function is done with the execution and is complete. Whenever we call the next() method, it executes the generator function until the 1st yield statement, and later it executes the next yield for every next() method call and continues until all the yield statements are executed.

Sample :

Originally published at https://www.shauryakalia.com/blog*.*

5 views

More from this blog

K

kaliaverse

17 posts

Shaurya Kalia is a full stack engineer who loves to code, read, travel, dance and train mixed martial arts. He writes about the same and believes in being the jack of all !