Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
2.
Generator Function
2.1.
Syntax
3.
Working of Generator Function
3.1.
Code
3.2.
Output
4.
Explanation
5.
Examples of Generator Function
5.1.
Having yield* 
5.1.1.
Output
5.2.
Passing arguments
5.2.1.
Output
5.3.
Having Return statement 
5.3.1.
Output
5.4.
Having Throw statement
5.4.1.
Output
5.5.
Generator example
5.5.1.
Output
6.
Frequently Asked Questions
6.1.
Define generator object.
6.2.
Describe yield and yield*.
6.3.
What are the uses of the generator function?
6.4.
What are the advantages of using the generator function?
7.
Conclusion
Last Updated: Mar 27, 2024

Generator Function in JavaScript

Author Pankhuri Goel
0 upvote

Introduction

Generators are functions that can be exited and re-entered at a later time. Across re-entrances, their context (variable bindings) will be preserved. On-demand, generators can return ("yield") many values one after the other. They work well with iterables, making it simple to design data streams.

Generators in Javascript, especially when used with Promises, are a valuable tool for asynchronous programming since they mitigate, if not altogether remove, difficulties with callbacks like Callback Hell and Inversion of Control. On the other hand, async functions offer a more straightforward answer to these issues.

Let's see more about generator functions in JavaScript.

Read more about, Fibonacci Series in Java

Generator Function

A generator function is defined identically to a regular function, except when it needs to generate a value, it uses the yield keyword instead of the return keyword. The yield statement halts the execution of a function and returns a value to the caller, but it keeps enough state for the function to restart where it left off. When the function is resumed, it continues where it left off after the last yield run.

There are three methods mainly associated with generators. 

  1. next(): It returns the value of yield.
  2. return(): It returns the value and then terminates the generator function.
  3. throw(): It throws an error and then ends the generator function.

Syntax

function* functionName(){
	yield1;
	yield2;
	//statements
	return;
}
Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Working of Generator Function

Let us see an example of a generator function and then understand its working.

Code

function* generator(a) {
  yield a;
  yield a + 5;
}

const gen = generator(2);

console.log(gen.next().value); // expected output: 2
console.log(gen.next().value); // expected output: 7

Output

Explanation

When you call a generator function, its body is not immediately executed; instead, an iterator object for the function is returned. When the iterator's next() method is invoked, the generator function's body is executed until the first yield expression, which specifies the value to be returned from the iterator or, in the case of yield*, delegates to another generator function, is reached. 

The next() method produces an object that has a value property that contains the yielded value and a done property that is a boolean that indicates if the generator has yielded its last value. When you call the next() method with an argument, it will restart the execution of the generator function, substituting the yield expression that was interrupted with the argument from next ().

When a generator's return statement is invoked, the generator will end (i.e. the done property of the object returned by it will be set to true). If a value is returned, the value property of the object returned by the generator will be set to that value

An error thrown inside the generator, similar to a return statement, will finish the generator unless it is captured within the generator's body. When a generator is completed, further next() calls will not run any of its code; instead, they will return an object of the following form: {value: undefined, done: true}.

Examples of Generator Function

Let us see some more examples of generator functions.

Having yield* 

function* anotherGenerator(a) {
  yield a + 5;
  yield a + 10;
  yield a + 15;
}

function* generator(a) {
  yield a;
  yield* anotherGenerator(a);
  yield a + 50;
}

var g = generator(5);

console.log(g.next().value); // Print: 5
console.log(g.next().value); // Print: 10
console.log(g.next().value); // Print: 15
console.log(g.next().value); // Print: 20
console.log(g.next().value); // Print: 55

Output

Passing arguments

function* logGenerator() {
  console.log(0);
  console.log(1, yield);
  console.log(2, yield);
  console.log(3, yield);
}

var g = logGenerator();

g.next();              // 0
g.next('Coding'); // 1 Coding
g.next('Ninjas');  // 2 Ninjas
g.next('Library'); // 3 Library

Output

Having Return statement 

function* yieldAndReturn() {
  yield "Yield";
  return "Return";
  yield "unreachable";
}

var g = yieldAndReturn();

console.log(g.next()); // { value: "Yield", done: false }
console.log(g.next()); // { value: "Return", done: true }
console.log(g.next()); // { value: undefined, done: true }

Output

Having Throw statement

function* yieldAndThrow() {
    yield 50;
    yield 70;
}

var g = yieldAndThrow();

console.log(g.next());
console.log(g.throw(new Error('An error found!!!')));
console.log(g.next());

Output

Generator example

function* powers(i){
     //infinite loop to calculate exponent
     for(let curr =i ; ; curr *= i){
         yield curr;
     }
}

for(let power of powers(2)){
     //controlling generator
     if(power > 64) break;
     console.log(power)
}

Output

For better understanding try it on an online javascript editor.

Frequently Asked Questions

Define generator object.

A generator object is returned by generator functions. Calling the next method on the generator object or utilising the generator object in a "for of" loop are two ways to use generator objects. A generating function returns the Generator object, which is compliant with both the iterable and iterator protocols.

 

Describe yield and yield*.

yield: stops the generator from running and returns the value of the expression written after the yield keyword.

yield*: iterates through the operands, returning each value until done is true.

 

What are the uses of the generator function?

The uses of the generator function are as follows:

→ Generators are memory efficient.

→ Iterators can be implemented more conveniently with generators.

→ Generators only run their code when it is needed.

→ When writing asynchronous tasks, generators allow us to write cleaner code.

 

What are the advantages of using the generator function?

The advantages of using generator functions are:

→ Lazy Evaluation: This is an evaluation paradigm that waits until the value of an expression is required before evaluating it. In other words, if the value isn't needed, it won't exist. It is based on demand.

→ Efficient Memory: Generators are memory efficient as a direct result of Lazy Evaluation. Only the values that are required are created. All of the values for typical functions must be pre-generated and saved in case they are needed later. With generators, however, the calculation is postponed.

Conclusion

In this article, we learned about generator functions in JavaScript and the various methods associated with it. We saw its working and its implementation through various examples.

We hope this blog has helped you enhance your knowledge. If you want to learn more, check out our articles on Iterables in javascript - Coding Ninjas Coding Ninjas StudioDate and Time in JavaScript | Part 1 - Coding Ninjas Coding Ninjas Studio and Date and Time in JavaScript | Part 2 - Coding Ninjas Coding Ninjas Studio.Do upvote our blog to help other ninjas grow.

Head over to our practice platform Coding Ninjas Studio to practice top problems, take various guided paths, attempt mock tests, read interview experiences, solve problems, participate in contests and much more!

Happy Reading!

Previous article
JavaScript eval() function
Next article
IIFE in JS
Live masterclass