Sub topic 4
Declaring Resources with using
This chapter assumes you know block scoping with let and const, how try/finally behaves, and how an object implements Symbol.dispose, which the previous chapter covered. Here you will use that protocol through the using declaration, which runs cleanup for you when a block ends.
The working model
A using declaration looks like a const declaration with a different keyword:
using res = openResource("db");It does three things:
- It evaluates the right-hand side and binds the result to
res, the same wayconstdoes. - It reads
res[Symbol.dispose]at the moment of declaration and remembers that method. - When control leaves the enclosing block, it calls the remembered method.
Control can leave the block in several ways: the last statement finishes, a return, a break or continue, or a thrown exception. Cleanup runs in all of these cases, which is the guarantee you used to get by writing try/finally yourself.
Replacing try/finally
Here is the same function written both ways. Run it in a runtime that supports explicit resource management, such as Node.js 24 or later. A later chapter covers tooling for other environments.
function openResource(name) {
console.log(`open ${name}`);
return {
name,
[Symbol.dispose]() {
console.log(`close ${name}`);
},
};
}
// Without using
function withoutUsing() {
const res = openResource("db");
try {
return `used ${res.name}`;
} finally {
res[Symbol.dispose]();
}
}
// With using
function withUsing() {
using res = openResource("db");
return `used ${res.name}`;
}
console.log(withoutUsing());
console.log(withUsing());
// open db
// close db
// used db
// open db
// close db
// used dbThe return value is computed first and the resource closes after that, but before the caller receives the value. In the using version the cleanup sits next to the acquisition, so a later edit to the function cannot separate them.
Cleanup on throw
function failing() {
using res = openResource("file");
throw new Error("boom");
}
try {
failing();
} catch (e) {
console.log(`caught ${e.message}`);
}
// open file
// close file
// caught boomThe disposer runs first and then the original error keeps propagating. Nothing catches or swallows it.
The binding behaves like const
A using binding cannot be reassigned:
{
using res = openResource("a");
// res = openResource("b"); // TypeError: Assignment to constant variable.
}This rule matters because the disposer was captured at declaration time. If you could reassign the binding, the variable would point at one object while cleanup ran on another. The object itself can still be mutated. Only the binding is fixed.
Common errors
| Mistake | What happens |
|---|---|
| The value has no `Symbol.dispose` method | `TypeError` thrown at the declaration, before the body runs |
| You expect cleanup when the function ends but declared inside an inner block | Disposal runs when the inner block exits |
| You call `res[Symbol.dispose]()` manually as well | The disposer runs twice unless it is idempotent |
| You return the resource from the function | The caller gets an object that has already been disposed |
Later chapters cover what happens with several declarations in one block, with null values, and with errors thrown during cleanup.
Exercise
What does this code print, and in what order? function f() { using r = openResource("x"); if (true) return "done"; console.log("unreachable"); } console.log(f());
Show answer
It prints "open x", then "close x", then "done". The early return still leaves the block, so the disposer runs before f's return value reaches console.log.
Exercise
Why does using forbid reassigning its binding, while still allowing the object's properties to change?
Show answer
The disposer is read and stored when the declaration runs. If the binding could be reassigned, the variable would refer to a different object than the one that gets cleaned up. Mutating properties does not change which object gets disposed, so it is allowed.