DEV Community

Cover image for Tips from open-source: Generator function in Javascript.
Ramu Narasinga
Ramu Narasinga

Posted on • Updated on

Tips from open-source: Generator function in Javascript.

As I was reading the Next.js source code, I saw a function name prefixed with "*". My first thought was “Is this a ponter in Javascript?”. After some research on Google, I found that these functions prefixed with "*" are called generator functions. I do not know about generator functions in Javascript until now.

Next.js source code has these generator functions defined in a class as shown below:

source code

Keep in mind that normally when you define these generator functions outside a class, they have the following syntax:

// source: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function\*
function\* generator(i) {
  yield i;
  yield i + 10;
  yield i + 20;
}

const gen = generator(10);

console.log(gen.next().value);
// Expected output: 10
console.log(gen.next().value);
// Expected output: 20
console.log(gen.next().value);
Enter fullscreen mode Exit fullscreen mode

Note: You can declare a generator like this — function *generator() or function * generator(). * can be separated with a white space or a line terminator.

Keys() as a generator function

public \*keys(): IterableIterator<string> {
    for (const key of Object.keys(this.headers)) {
      const name = key.toLowerCase()
      yield name
    }
  }
Enter fullscreen mode Exit fullscreen mode

This code snippet is from header.ts in Next.js source code. I asked myself a question “Why a keys() function is a generator function?”

I pasted this code in the ChatGPT and it introduced me to a term “Memory efficiency”. Hang on a minute, how?

Copy the below and paste in your browser

const exampleObject = {
  firstName: "John",
  lastName: "Doe",
  age: 30
};

// Implementing keys() method using a generator function
exampleObject.keys = function\* () {
  for (const key in this) {
    yield key;
  }
};

// Now, you can iterate over the keys of exampleObject using a for...of loop
for (const key of exampleObject.keys()) {
  console.log(key);
}

// output:
firstName
VM247:16 lastName
VM247:16 age
VM247:16 keys
Enter fullscreen mode Exit fullscreen mode

But if you try to log the keys(), the following are the results:

results

Instead of generating all keys at once and storing them in an array, a generator function produces keys on-the-fly as they are requested.

Further reading links:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
  2. https://stackoverflow.com/questions/47027191/do-suspended-generator-functions-have-performance-costs

Conclusion:

function* keys(), turns out is a generator function, not a pointer in anyway. You want to use this when you want to generate keys, entries, values on the fly.

Generator functions do not consume execution time and they reside in memory until used.

Get free courses inspired by the best practices used in open source.

About me:

Website: https://ramunarasinga.com/

Linkedin: https://www.linkedin.com/in/ramu-narasinga-189361128/

Github: https://github.com/Ramu-Narasinga

Email: ramu.narasinga@gmail.com

Learn the best practices used in open source.

Top comments (1)

Collapse
 
riehlejoubert profile image
RiehleJoubert

Exploring generator functions in JavaScript opens up new avenues for efficient asynchronous programming and streamlined code execution. Reddyanna