Question

27.

What are generator functions in JavaScript

Answer

Generator functions in JavaScript are a special class of functions that simplify the task of writing iterators. A generator is defined by the function keyword followed by an asterisk (*) and uses the yield keyword to pause its execution and return an intermediate value. The function execution can later be resumed from the same point, maintaining its context (variable bindings, the value of this, etc.).

Key Characteristics:

  • Pausing Execution: Generator functions allow you to pause their execution at a certain point and then continue from where they left off, which is not possible with regular functions.
  • Stateful Iteration: They can maintain their state between executions, making them ideal for creating iterators where you need to keep track of your current position in a collection or series of operations.
  • Yield: The yield keyword is used to pause the function execution and return a value. The function will resume when a next() call is made on the generator object.
  • Generator Object: When a generator function is called, it doesn't execute its code. Instead, it returns a generator object that conforms to both the iterable protocol and the iterator protocol.

Syntax:

function* myGenerator() {
  yield 'Hello';
  yield 'World';
}

Using Generator Functions:

const gen = myGenerator();

console.log(gen.next().value); // "Hello"
console.log(gen.next().value); // "World"
console.log(gen.next().value); // undefined
  • .next() Method: Each call to the generator object's next() method executes the generator function from the current yield statement to the next yield statement. It returns an object with two properties: value, which is the yielded value, and done, which is a boolean indicating whether the generator function has fully completed.
  • yield Expression: Pauses the execution of the generator function and returns the yielded value to the caller. Execution can later be resumed.
  • Completion: Once a generator function has no more code to execute or encounters a return statement, subsequent calls to next() return an object with the properties value set to undefined (unless return specifies a value) and done set to true.

Advanced Use Cases:

  • Passing Values to next(): You can pass a value back to the generator through the next() method, which will be the result of the last yield expression paused at.
  • for...of Loops: Since generator objects are iterable, you can use them in for...of loops directly to iterate over the values they generate.
  • Handling Asynchronous Operations: Generators can be used to handle asynchronous operations in a synchronous-like manner, especially when used with Promises and utility functions like co or libraries like async/await (which are syntactic sugar over generators and promises).

Support us ❤️

Buy Us A Coffee