How to create a generator function in JavaScript
Creating generator functions in JavaScript enables lazy evaluation and controlled iteration, providing memory-efficient solutions for large datasets and complex iteration patterns.
With over 25 years of experience in software development and as the creator of CoreUI, I’ve used generators extensively for data streaming, pagination handling, and asynchronous control flow.
From my expertise, the most powerful approach is using the function* syntax with yield statements to create functions that can pause and resume execution.
This pattern provides elegant solutions for scenarios requiring on-demand value generation and stateful iteration.
Use function* syntax with yield statements to create generator functions that can pause and resume execution.
function* numberGenerator(max) {
let current = 1
while (current <= max) {
yield current
current++
}
}
const gen = numberGenerator(5)
console.log(gen.next().value) // 1
console.log(gen.next().value) // 2
Here function* declares a generator function that uses yield to pause execution and return values. Each call to next() resumes execution until the next yield statement. The generator maintains its internal state between calls, remembering variable values and execution position. Generators are lazy - they only compute values when requested, making them memory-efficient for large or infinite sequences.
Best Practice Note:
This is the same approach we use in CoreUI data processing for handling large datasets, implementing custom iterators, and managing complex asynchronous workflows. Generators are perfect for pagination, data streaming, and any scenario where you need to process large amounts of data incrementally rather than all at once.



