Loading...

What is yield keyword in Node.js? Complete guide to yield in Node.js

What is yield keyword in Node.js? Complete guide to yield in Node.js

Over the years, JavaScript has evolved so much. From being a primary scripting language made for the Netscape Navigator to make websites more dynamic and interactive to the multipurpose and the most loved programming language ever. Even after such a success of the language, many JavaScript features are not known to many of us. And, even if we have heard them, we don’t clearly understand them. One such feature is the Generator functions and the yield keyword.

In this article, we will understand in detail what are JavaScript generator functions and what is the yield keyword. Further, we will discuss some of its applications that we can use in day-to-day coding. As an added bonus, we will also discuss some extra methods that we can use with the generator instances we create. Following this article, you will get a clear grasp of the working of generator functions and their applications.

What are JavaScript generator functions?

From our current understanding of JavaScript, we know that a JavaScript function cannot be paused. But did you know it is possible to pause the execution of a function in JavaScript? I am sure most of you didn’t. A function in JavaScript can be paused or stopped at a particular instance, and it is possible with the help of JavaScript generator functions.

In JavaScript, a generator function is one that we can pause and resume multiple times. It also generates (or yields) a value every time it pauses.

Pausing a function may sound silly. Why would anyone want to pause a function execution? There are many uses of generators in JavaScript, one of which is using them as iterators. Yes, the iterators that we use almost every day in JavaScript can be written with ease using generators. We can use these custom iterators for various simple to advanced use cases.

Creating a JavaScript generator function

Now that we are familiar with JavaScript generator functions, let us look at the syntax to declare it in JavaScript. The below code demonstrates the declaration of a JavaScript generator function:

function* genFunc() { // Generator function body }
Code language: JavaScript (javascript)

You can notice the * symbol following the function keyword. The * symbol (also called asterisk) signifies that it is a generator function declaration. We can write the code as usual inside the generator function. To pause its execution and generate or yield a value, we will use the yield keyword.

The yield keyword

We use the yield keyword to pause a generator function’s execution. On encountering the yield keyword, two things happen: the function’s execution stays at that particular occurrence of the yield keyword and the generator function generates (or yields) a value that follows the yield keyword.

The below code demonstrates the declaration of a JavaScript generator function and the use of the yield keyword:

function* genFunc() { yield 'Hello'; yield 'from'; yield 'Codedamn!'; }
Code language: JavaScript (javascript)

The function execution pauses at every occurrence of the yield keyword, i.e., at line numbers 2, 3, and 4. Also, at each pause, the function will yield the value “Hello”, “from”, and “Codedamn!”, respectively.

How to use JavaScript generator functions?

We don’t use the generator function directly. Firstly, we create a generator object using a JavaScript generator function. The generator object has a lot of methods to use. The most useful method that we will be talking about is the next() method.

The next() method runs the generator function till the next yield occurrence. The function then pauses at that instance, and the value yielded by the generator function is returned by the next() method.

Here is how we create a generator object using the generator function:

function* genFunc() { yield "Hello"; yield "from"; yield "Codedamn!"; } const genObj = genFunc(); console.log(genObj)
Code language: JavaScript (javascript)

We have used the generator function that we previously wrote. On logging the generator object on the console, we can see that its a generator object:

A generator object.
A generator object.

The most useful method for us in the generator object is the next() method. Let us call the next method and observe the value returned by it:

function* genFunc() { yield "Hello"; yield "from"; yield "Codedamn!"; } const genObj = genFunc(); const val1 = genObj.next(); console.log(val1)
Code language: JavaScript (javascript)

We have stored the value returned by it inside a variable val1. Let us log the value of the variable val1 onto the console:

The return value of the next() method.
The return value of the next() method.

The variable val1 is an object having two properties: value and done. The value property contains the actual value yielded by the generator function, and the done property contains a boolean that tells us if more yield statements are left. A true value on the done property indicates that more yield statements are left inside the generator function and a false value on the done property indicates that no more yield statements are left inside our generator function.

We must note that by using a generator function, we can have more than one generator object. All the objects created using a generator function are independent of each other, i.e., they have their own iterations which do not interfere with the other generator objects of the same generator function.

Applications of JavaScript generator functions

We have seen the working of JavaScript generator functions and the use of the yield keyword. But you might wonder why we need generator functions in JavaScript. The answer lies in its various application in a large number of libraries. Even if we keep JavaScript libraries aside, there are many instances where we can use JavaScript generator functions to simplify day-to-day tasks.

Infinite loops

In JavaScript, we cannot make infinite loops, as they will block the main thread. JavaScript is single-threaded, having only one main thread, which is blocked; other functions won’t work since the main thread will be occupied processing the infinite loop. But we have a workaround for that. We just saw that JavaScript generator we can pause the JavaScript generator functions. Using this knowledge, we can implement an infinite loop. Here is the implementation:

function* infiniteLoop() { let x = 0; while(true) { yield x++; } } const genObj = infiniteLoop(); console.log(genObj.next()); console.log(genObj.next()); console.log(genObj.next());
Code language: JavaScript (javascript)

Here, on each iteration, due to the yield keyword, the function execution is paused. We resume it by using the next() method on the generator object. This way, we can have an infinite loop without blocking the main thread:

The output of the infinite loop generator function.
The output of the infinite loop generator function.

Iterators

Using JavaScript generator functions, we can build our custom iterators. The application of these custom iterators may range from simple iterations to some complex calculations. Here is a sample code to use JavaScript generator functions to convert an array to an iterator:

function* iter(arr) { for (let x = 0; x <= arr.length; x++) { yield arr[x]; } }
Code language: JavaScript (javascript)

Using the next() method, we can iterate over the set of values. Using the done property on the object returned by the next() method, we can loop over the iterator using a simple while loop:

function* iter(arr) { for (let x = 0; x <= arr.length; x++) { yield arr[x]; } } const genObj = iter(['Hello', 'from', 'Codedamn!']); let val = genObj.next(); while(!val.done) { console.log(val) val = genObj.next(); }
Code language: JavaScript (javascript)

Running the above piece of code using Node.js, the following output gets generated:

The output of our iterator implementation.
The output of our iterator implementation.

Conclusion

Over the years, JavaScript has evolved so much. Before ECMAScript 2015, we had no option to pause a function execution in JavaScript. But in ECMAScript 2015, Generators were added in JavaScript. A generator function is one that we can pause and resume multiple times. It also generators (or yields) a value every time it pauses. To pause the function execution, we use the yield keyword. Today generators constitute a huge portion of JavaScript libraries. Even if we keep JavaScript libraries aside, there are many instances where we can use JavaScript generator functions to simplify day-to-day tasks.

You can find the complete source code using the following link.

This article hopefully provided you with some new information. Share it with your friends if you enjoy it. Also, please provide your feedback in the comments section.

Thank you so much for reading 😄

Sharing is caring

Did you like what Varun Tiwari wrote? Thank them for their work by sharing it on social media.

0/10000

No comments so far