What are Generators in JavaScript

CodeyMaze
3 min readMar 5, 2022

--

Generators are special types of functions that can be paused and then resumed again. These functions do not get executed when called. It returns an object that is used to manage code execution. This object is referred to as “Generator Object”.

To make a function generator function, we have to add a star ( * ) after the function keyword.

function* genFunc() { // Code Block }

Yield is an operator that is used inside the generator function to yield the result of the function. With the help of yield, a generator function can pause itself. Generator functions send the output with the help of the ‘yield’ operator.

There is a special method ‘next’ which we can call with the help of a generator object. The function code execution is initially paused at first. Calling next() on the generator object resumes execution and yield inside the function pauses execution.

In the above example, calling next() on the generator object will output 1 then function execution gets stopped until the next call of the next() method.

Calling next() again will output 2. This will continue till all the yield statements get executed. There will be one more variable that gets displayed named ‘done’. The value of ‘done’ will be a Boolean value true/false. False means if there are more yield statements to be executed. This will be true when all the yield statements get executed.

Let’s see the output of the above :

When all the yield statements get executed, ‘done’ will be true and value will be undefined.

Return value of Generators

We can also return any value when all the yield statements get executed. We can return from the generator function with the help of the return keyword.

Let’s see the output :

Now in place of undefined, it outputs ‘All Done’ when all the yield statements gets executed. Calling next() again will output done true and value undefined.

Generators are Iterable

Generators are iterable i.e. we can loop over generator values using for…of

It is going to output 1 2 3. It’s not going to print 4 because for..of iteration ignores the last value, when done is true. so if we want results to be shown like 1 2 3 4 then we must return them with yield.

As generators are iterable we can use a spread operator as well.

Its going to print [0,1,2,3]

Subscribe to our Youtube channel for more videos :

https://www.youtube.com/channel/UCEXWe9R6-ppk4zhNo2JbtmQ

--

--

CodeyMaze
CodeyMaze

Written by CodeyMaze

Crafting Solutions Through Code & Words https://codeymaze.com Feel free to follow me :)

No responses yet