Generator

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Generator Functions

JS · Functions
Syntax
function* name() { yield value; }
Example
function* idGenerator(start = 1) {
  let id = start;
  while (true) {
    yield id++;
  }
}
const ids = idGenerator(100);
console.log(ids.next().value); // 100
console.log(ids.next().value); // 101
console.log(ids.next().value); // 102

Note Generators are lazy -- they produce values on demand. Execution pauses at each yield and resumes when next() is called.

PYPython

Generators with yield

PY · Functions
Syntax
def gen():
    yield value
Example
def countdown(n: int):
    while n > 0:
        yield n
        n -= 1

for tick in countdown(3):
    print(tick)

# Generators are lazy - values produced one at a time
nums = countdown(1_000_000)
print(next(nums))
Output
3
2
1
1000000

Note Generators produce values lazily, consuming almost no memory regardless of size. They are single-use: once exhausted, they cannot be restarted.

Frequently asked questions

How does JavaScript handle generator?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Generator Functions" snippet in JavaScript uses `function* name() { yield value; }`.
Which code does the JavaScript example use?
The "Generator Functions" snippet uses `function* name() { yield value; }`, from the Functions section of the JavaScript cheat sheet.
Which stacks cover "generator" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Generator Functions": Generators are lazy -- they produce values on demand. Execution pauses at each yield and resumes when next() is called.