JavaScript Reference ยท Statements and Declarations
The using declaration
Reference for the JavaScript using declaration and await using: resources that are disposed automatically at scope end via Symbol.dispose, with examples.
A using declaration binds a variable like const, and also promises that the value will be disposed when the surrounding block ends. The value must have a [Symbol.dispose]() method (or be null or undefined). When the scope exits, whether normally, by return, break or by an exception, the engine calls that method for you.
This is the language's built-in version of "close this file / release this lock in a finally block".
{
using resource = openResource();
// use it...
} // resource[Symbol.dispose]() runs here
Try it
This feature is recent. If your browser does not support it, the example reports a syntax error; read the code and the expected output below it instead.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
using name = expression; using a = x, b = y; await using name = expression; // async disposal, inside async functions or modules
| Part | Description |
|---|---|
expression |
An object with [Symbol.dispose](), or null/undefined (nothing to dispose). |
await using |
Requires [Symbol.asyncDispose]() (or falls back to Symbol.dispose) and awaits it. |
Usage notes
- Reverse order. Resources are disposed in the opposite order of declaration, like a stack.
- Block-scoped and constant. Like
const, the binding cannot be reassigned. It can also appear inforheads, as infor (using item of items). - Errors during disposal. If both the body and a disposer throw, the errors are combined in a
SuppressedError. - Helper objects.
DisposableStackandAsyncDisposableStackmanage several resources dynamically where support exists. - Not garbage collection.
usinggives deterministic cleanup at a known point, unlike finalizers. - Fallback. Where unsupported, use
try...finallyand call the cleanup yourself. - Naming.
usingis a contextual keyword; it is still a valid identifier elsewhere.
Browser support
Explicit resource management is a recent addition and support is limited and still spreading across engines. Check a compatibility table before using it in production, and use try...finally where you must support older environments.
Related
try...catch...finally,constSymbol, well-known symbols- Lesson: Errors