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:
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);
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
}
}
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
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:
- https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function*
- 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
Top comments (1)
Exploring generator functions in JavaScript opens up new avenues for efficient asynchronous programming and streamlined code execution. Reddyanna