Iterator closing on early exit
Quick answer
Consumers such as for...of close an iterator when they leave a loop early. Closing offers the iterator a chance to release resources.
How it works
On break or a return from the enclosing function, for...of invokes the optional return() method of the iterator if present. A generator’s finally block can run during closing. Destructuring that stops before exhaustion can also close the iterator. Natural exhaustion does not require the separate close call. Not every possible failure calls return; errors from next itself are a distinct case. Manual next consumers should define their cleanup policy.
const it={ [Symbol.iterator](){return this;},next(){return {value:1,done:false};},return(){console.log("closed");return {done:true};}}; for(const x of it){console.log(x);break;}Expected output in Node.js:
1closedThe early break calls return.
function* g(){try{yield 1;yield 2;}finally{console.log("cleanup");}} const [first]=g(); console.log(first);Expected output in Node.js:
cleanup1Destructuring closes after obtaining one element.
Common mistakes
Do not assume every iterator has return or that manual next calls automatically close it. Do not yield again inside cleanup unless the resulting incomplete close is intentional.
Practice
Compare the log from a natural traversal with break and one-element destructuring.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Iterator closing on early exit — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which method is used to request early iterator cleanup?
Does ordinary exhaustion necessarily make a separate return call?
Which construct can run cleanup during generator closing?
What is the exact console output in Iterator closing on early exit example 1?
const it={ [Symbol.iterator](){return this;},next(){return {value:1,done:false};},return(){console.log("closed");return {done:true};}}; for(const x of it){console.log(x);break;}What is the exact console output in Iterator closing on early exit example 2?
function* g(){try{yield 1;yield 2;}finally{console.log("cleanup");}} const [first]=g(); console.log(first);