Sub topic 5
When and in What Order Resources Are Disposed
This chapter assumes you already know how a using declaration binds a disposable object and that you are comfortable with block scoping, try/catch/finally, and generators. The examples run in any runtime that ships explicit resource management natively, such as Node.js 24 or later and Chrome 134 or later.
Knowing that using "cleans up at the end of the block" is not enough to reason about real code. You also need answers to these questions: which exits count as the end of the block, which resources get registered, what order they are cleaned up in, and when the dispose method is looked up. This chapter answers each one.
The Mental Model: A Per-Scope Stack
Every block, function body, or module body that contains a using declaration gets a hidden list of resources. Each time a using declaration runs, the engine pushes the value and its dispose method onto that list. When control leaves the scope, the engine takes entries off the end of the list one at a time and calls each dispose method.
That gives three rules:
- A resource is registered only when its declaration actually runs.
- Disposal happens at the moment control leaves the scope, whatever the reason it leaves.
- Resources are disposed in reverse order of registration: last in, first out.
Reverse order matters because later resources often depend on earlier ones. A statement handle created from a connection should be closed before the connection itself. A transaction should end before its connection is released. Declaring resources in dependency order means cleanup runs in the safe order without any extra code.
All the examples below use this helper:
function res(name) {
console.log(`open ${name}`);
return {
name,
[Symbol.dispose]() {
console.log(`close ${name}`);
},
};
}Every Exit Path Triggers Disposal
The scope is left whenever execution completes normally, hits return, throws, or is redirected by break or continue. Each of these runs disposal.
| Exit path | Disposal runs? | When, relative to the exit |
|---|---|---|
| Falling off the end of the block | Yes | After the last statement |
| `return expr` | Yes | After `expr` is evaluated, before the caller receives the value |
| `throw` (or an uncaught error from a call) | Yes | Before any enclosing `catch` or `finally` runs |
| `break` / `continue` | Yes | Before control jumps to its target |
| Generator `yield` | No | The scope is suspended, not exited |
| Generator `return()` or `throw()` while suspended | Yes | When the generator resumes and unwinds |
Early return registers only what ran
function early(flag) {
using a = res("a");
if (flag) return "early";
using b = res("b");
return "late";
}
console.log(early(true));
// open a
// close a
// early
console.log(early(false));
// open a
// open b
// close b
// close a
// lateWhen flag is true, the declaration of b never runs, so b is never opened or registered. Disposal covers only what is on the stack. You never need to track by hand which resources were actually acquired.
Loop bodies dispose on every iteration
A loop body is a block, so a using inside it is disposed at the end of each iteration. That includes iterations cut short by continue or break.
for (let i = 0; i < 3; i++) {
using r = res(`r${i}`);
if (i === 1) continue;
if (i === 2) break;
console.log(`body ${i}`);
}
// open r0
// body 0
// close r0
// open r1
// close r1
// open r2
// close r2Resources do not pile up across iterations. Each one is closed before the next iteration opens its own.
The Return Value Is Computed Before Disposal
With return expr, the expression is evaluated first and disposal runs afterward. That lets you read from a resource in the return statement itself:
function readName() {
using r = res("file");
return r.name.toUpperCase();
}
console.log(readName());
// open file
// close file
// FILEThe close file line prints before FILE because the caller only receives the value once disposal has finished.
The same applies to closures. A callback that captures r and runs later, for example through setTimeout or a promise continuation, sees the object after it has been disposed. using ties cleanup to the lexical scope, not to the last reference.
Disposal Happens Before catch and finally
When a using sits directly inside a try block, that block is the scope. It exits before the engine moves to catch or finally, so cleanup has already happened when your handler runs.
function failToOpen() {
throw new Error("cannot open c");
}
try {
using a = res("a");
using b = res("b");
using c = failToOpen();
console.log("unreached");
} catch (e) {
console.log(`caught: ${e.message}`);
} finally {
console.log("finally");
}
// open a
// open b
// close b
// close a
// caught: cannot open c
// finallyThis example also shows partial acquisition. The initializer for c throws, so c is never registered, while a and b are still disposed in reverse order. With manual try/finally you would need nested blocks or a flag for each resource to get this right.
If a dispose method throws, the engine still calls the remaining dispose methods on the stack and then reports the errors together. The chapter on SuppressedError covers how those errors are combined.
The Dispose Method Is Captured at Declaration Time
The engine reads value[Symbol.dispose] when the using declaration runs, not when the scope exits. If the property is missing or not callable at that moment, the declaration throws a TypeError right away, before any of the block's later code runs. If the property changes afterward, the change has no effect.
const obj = {
[Symbol.dispose]() {
console.log("original dispose");
},
};
{
using x = obj;
obj[Symbol.dispose] = () => console.log("replaced dispose");
}
// original disposeTwo consequences follow:
- Mistakes show up early. A non-disposable value fails at the declaration, so you never discover at cleanup time that nothing can be cleaned up.
- You cannot swap cleanup behavior partway through a block by mutating the object. If cleanup has to depend on state, put the decision inside the dispose method.
The binding is also constant. Assigning to it, as in x = other, throws a TypeError just as it would for const. The registered entry always points to the original value.
The same object registered twice is disposed twice
Each declaration pushes its own entry, even when both entries hold the same object:
const shared = res("shared");
{
using first = shared;
using second = shared;
}
// open shared
// close shared
// close sharedThis is one reason disposable objects should be idempotent: the second call should notice the object is already closed and return without doing anything.
Suspended Scopes: Generators
A yield suspends a generator's scope without exiting it, so resources declared inside stay open while the generator is paused.
function* numbers() {
using r = res("gen");
yield 1;
yield 2;
}
const it = numbers();
console.log(it.next().value);
console.log("generator paused, resource still open");
it.return();
// open gen
// 1
// generator paused, resource still open
// close genCalling return() resumes the generator as if a return statement had run at the paused yield, and that unwinds the scope and disposes r. A for...of loop calls return() for you when it exits early. If you iterate by hand and simply drop the iterator, the generator never resumes, and its resources are never disposed. Garbage collection does not run dispose methods.
Module Scope
In an ES module, the module body is a scope too. A top-level using is disposed when the module finishes evaluating, which happens long before the program ends. Do not use a top-level using for a resource that other modules or later event-loop work will need. Use const and close the resource from an explicit shutdown path. The chapter on syntax rules lists where using is allowed.
Nested Scopes
Each block keeps its own stack. An inner block disposes its resources when it exits, before the outer block continues:
{
using outer = res("outer");
{
using inner = res("inner");
console.log("inner work");
}
console.log("outer work");
}
// open outer
// open inner
// inner work
// close inner
// outer work
// close outerTo release a resource before the end of a function, wrap its use in a bare block. This is the idiomatic way to shorten a resource's lifetime.
Exercise
What does this code print?
function run() {
using a = res("a");
for (const n of [1, 2]) {
using b = res(b${n});
if (n === 2) return n * 10;
}
using c = res("c");
return 0;
}
console.log(run());
Show answer
"open a", "open b1", "close b1", "open b2", "close b2", "close a", then "20". The first iteration disposes b1 when its body ends. In the second iteration, return evaluates 20, then the loop body scope disposes b2, then the function scope disposes a. The declaration of c never runs, so c is never opened or disposed.
Exercise
A teammate writes function openLog() { using file = openFile("app.log"); return file; } and reports that writes to the returned file fail with "file closed". Explain why and give the fix.
Show answer
The using declaration disposes file when openLog's scope exits, and that happens right after the return value is evaluated and before the caller receives it. The caller gets an object that is already closed. Declare it with const inside openLog (const file = openFile("app.log"); return file;) and let the caller write using log = openLog(); so the caller's scope owns the cleanup.
Exercise
Inside a block, using conn = pool.get(); runs. Then conn[Symbol.dispose] = null; runs before the block ends. What happens at block exit, and why?
Show answer
The original dispose method still runs normally. The engine read conn[Symbol.dispose] and stored it when the using declaration ran, so replacing the property afterward has no effect on the registered cleanup.