⚡ Fix a Generator Function Leaking Across Iterations
A generator function’s local variables persist on its own suspended execution context between yield calls by design, which is exactly what makes generators useful — but a generator that captures a mutable object from its outer scope and yields a reference to that same object on every iteration hands every consumer a view into state that keeps changing underneath them after each .next() call, instead of a fresh snapshot per iteration.
🔎 The Problem
function* readings(sensor) {
const buffer = { value: null };
while (true) {
buffer.value = sensor.read();
yield buffer; // same object reference every time
}
}
const gen = readings(sensor);
const a = gen.next().value;
const b = gen.next().value;
console.log(a.value === b.value); // true - "a" silently changed too
✅ Fix: Yield a Fresh Value or Copy Instead of a Shared Reference
- Yield a new object literal on each iteration (
yield { value: sensor.read() }) instead of mutating and re-yielding the same captured object, so every consumer gets an independent snapshot. - If the buffer object is kept around deliberately for performance, document that loudly and have consumers read the value out immediately rather than holding onto the yielded reference across iterations.
- Add a quick regression test that calls
.next()twice, stores both results, and asserts they’re independent — this bug is invisible in a quick console log but obvious the moment two results are compared.
A generator’s job is to pause and resume state, not to hand out the same mutable object dressed up as a new result each time.





