ae4744a771771389bea0
·2 min read

function* (Generator Functions) in JavaScript

javascript
typescript
4d5fd787ac74e0caa4f7

Sohan R. Emon

Developer, Learner, Tech Enthusiast

Generator functions are an intriguing feature in JavaScript that allow you to create iterators. These iterators can yield values one at a time, giving you control over the flow of your program. In this article, we'll dive into generator functions and explore how they work and why you might want to use them in your projects.

javascript
// Generator Function Example
function* countToFive() {
  for (let i = 1; i <= 5; i++) {
    yield i;
  }
}

const counter = countToFive();

console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3
console.log(counter.next().value); // 4
console.log(counter.next().value); // 5
console.log(counter.next().value); // undefined

What is a Generator Function?

A generator function is defined using an asterisk (*) symbol after the function keyword. It contains one or more yield statements. When you call a generator function, it doesn't execute immediately. Instead, it returns an iterator called a generator object. You can then use this object to control the execution of the function.

Basic Usage

Let's look at a simple example of a generator function:

javascript
function* countToFive() {
  for (let i = 1; i <= 5; i++) {
    yield i;
  }
}

In this function, we use a for loop to count from 1 to 5, and yield each value. To use this generator, we create an instance of it and call next() to get the next value:

javascript
const counter = countToFive();

console.log(counter.next().value); // 1
console.log(counter.next().value); // 2
console.log(counter.next().value); // 3
console.log(counter.next().value); // 4
console.log(counter.next().value); // 5
console.log(counter.next().value); // undefined

Advantages of Generator Functions

  1. Lazy Evaluation: Generator functions follow a lazy evaluation approach, meaning they only compute values as you request them. This can be very efficient when dealing with large datasets or time-consuming computations.

  2. Memory Efficiency: Since generator functions don't generate all values at once, they can save memory compared to eagerly computed collections like arrays.

  3. Easy to Implement Iterators: Generator functions simplify the process of creating custom iterators, making your code more readable and maintainable.

  4. Control Flow: Generator functions give you fine-grained control over the flow of your program, allowing for pausing and resuming execution as needed.

So, next time you find yourself dealing with a series of values, consider harnessing the power of generator functions to simplify your code and improve performance.

Found this useful?