DEV Community

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

Posted 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:\*
function\* generator(i) {
  yield i;
  yield i + 10;
  yield i + 20;

const gen = generator(10);

// Expected output: 10
// Expected output: 20
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()) {

// output:
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:


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:



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.

Top comments (1)

riehlejoubert profile image

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