Sub topic 9
Where using Is Allowed and What It Forbids
This chapter assumes you are comfortable with block scoping for let and const, the try/finally statement, and async functions. Earlier chapters showed what using and await using do at runtime. This one covers the grammar: where the parser accepts these declarations, the forms it rejects, and the places where the code still parses but means something you did not intend.
The basic rule is that a using declaration behaves like a const declaration, but it is only allowed where a scope has a clear exit point at which disposal can run. Most of the restrictions follow from that.
The core rules at a glance
| Rule | Allowed | Rejected |
|---|---|---|
| Must have an initializer | `using r = open();` | `using r;` |
| Plain identifier only | `using r = open();` | `using { a } = open();` |
| Multiple declarators | `using a = f(), b = g();` | none |
| Binding is read-only | reading `r` | `r = other;` (TypeError at runtime) |
| Must sit in a scope with an exit | blocks, function bodies, loop heads, modules | top level of a classic script |
| Not a single-statement body | `if (x) { using r = f(); }` | `if (x) using r = f();` |
| Not exportable | `using r = f(); export { }` | `export using r = f();` |
| `for...in` head | none | `for (using k in obj)` |
| `await using` needs an await context | async functions, async generators, module top level | sync functions, classic scripts |
The sections below explain each rule and show the edge cases.
Declaration shape: initializer, identifier, read-only
A using declaration needs a value at the moment of declaration, because the runtime records the resource and its dispose method right then. A declaration without an initializer gives the runtime nothing to register, so the parser rejects it.
Destructuring is also forbidden. If you wrote using { reader, writer } = openPair(), it would be unclear what to dispose: the pair object, or each property. The proposal settles this by allowing only a plain identifier. To dispose the parts, give each its own declaration, or use the whole object as the resource and take the parts from it afterward.
function openPair() {
const make = (name) => ({ name, [Symbol.dispose]() { console.log(`close ${name}`); } });
return { reader: make("reader"), writer: make("writer") };
}
{
const pair = openPair();
using reader = pair.reader;
using writer = pair.writer;
console.log(`${reader.name} + ${writer.name}`);
}
// reader + writer
// close writer
// close readerThe binding is read-only, like const. Assigning to it throws a TypeError at runtime ("Assignment to constant variable"). The parser does not catch this. Disposal always uses the value captured at declaration, so reassignment could never redirect cleanup. The rule exists so that the name you read always refers to the object that will be disposed.
The binding also has a temporal dead zone, like const. Reading it before its declaration line throws a ReferenceError.
Where the declaration can appear
The parser accepts using inside any of these:
- A block statement
{ ... } - A function, method, arrow function, or generator body
- A class
static { ... }block - The head of a
for,for...of, orfor await...ofloop - A
switchstatement's case block - The top level of an ES module
The one place left out is the top level of a classic script, meaning a <script> tag without type="module", or code parsed as a Script. A script's top level has no single exit point. Later scripts share the same global lexical scope, so the runtime has no moment at which "the scope ended". Wrap the code in a block or function, or load it as a module.
Single-statement bodies
if (ready) using r = open(); is a syntax error, just as if (ready) let x = 1; is. A declaration needs a scope, and a bare statement body is not one. Add braces, which also makes it clear that r is disposed as soon as the if body ends.
switch statements
All the case clauses of a switch share one block. A using inside a case is therefore disposed when the whole switch exits, not when control falls out of that case. The binding is also visible in later cases, where it is in its temporal dead zone if its own case did not run. Put each case body in its own braces so each resource gets its own scope:
function handle(kind) {
const res = (n) => ({ [Symbol.dispose]() { console.log(`dispose ${n}`); } });
switch (kind) {
case "a": {
using r = res("a");
console.log("handling a");
break;
}
case "b": {
using r = res("b");
console.log("handling b");
break;
}
}
console.log("after switch");
}
handle("a");
// handling a
// dispose a
// after switchGenerators
Inside a generator, a using resource lives as long as the generator's scope stays active, which can cover many yields. It is disposed when the generator finishes, throws, or is closed with return(). A for...of loop that exits early calls return() for you. A generator you advance by hand and then abandon is never closed, so its resources are never disposed.
await using needs an await context
await using has the same rules as using, plus the rules of await. It is allowed only where await is allowed: inside async functions, inside async generators, and at the top level of a module (as top-level await). Inside a regular function, await using is a syntax error.
That means you cannot hide async disposal behind a synchronous function signature. If a function needs to await cleanup, it has to be async, and callers see that it returns a promise.
Parsing traps: code that is legal but wrong
using is a contextual keyword. It is still a valid identifier, so let using = 1; is fine. To keep old code working, the parser treats using as a declaration only when the next token makes that unambiguous. In some cases, code that looks like a declaration parses as something else without any error.
Line breaks
No line break is allowed between using and the binding name. Between await, using, and the name in await using, no line break is allowed either. If you add one, automatic semicolon insertion splits the code into separate statements:
using
res = open();
// parses as: using; res = open();This throws a ReferenceError if no variable named using exists. If one does exist, nothing gets disposed and no error tells you so. Formatters keep the declaration on one line, but hand-edited code can break it.
Square brackets
using [a] = value; does not declare a destructured resource. It parses as an assignment to a computed property: using[a] = value. It only fails at runtime, and only if using is undefined.
for...of with a binding named of
for (using of items) is a for...of loop that assigns each element to a variable called using. It is not a declaration. Avoid naming a resource of.
for...in is rejected
for (using k in obj) is a syntax error. Property-name strings are not disposable, so the form is disallowed. A classic for (using r = open(); cond; step) loop head is allowed. Its resource is declared once and disposed when the loop ends, not on each iteration. The next chapter covers per-iteration disposal with for...of.
No export
export using conn = open(); is a syntax error. A module-level resource is disposed when the module body finishes evaluating. An exported binding would point at an object that had already been disposed.
Checking the rules yourself
The Function and AsyncFunction constructors parse a string as a function body, so you can test the grammar without crashing your program. Run this in a runtime with native support, such as Node.js 24 or a recent Chromium.
const AsyncFunction = (async () => {}).constructor;
function check(label, source, Ctor = Function) {
try {
new Ctor(source);
console.log(`parses ${label}`);
} catch (e) {
console.log(`rejected ${label}: ${e.constructor.name}`);
}
}
check("basic", "using r = null;");
check("no initializer", "using r;");
check("object destructuring", "using { a } = obj;");
check("bracket form", "using [a] = obj;"); // parses as member assignment
check("line break", "using\nr = null;"); // parses as two statements
check("if body", "if (x) using r = null;");
check("braced if body", "if (x) { using r = null; }");
check("for...in head", "for (using k in obj) {}");
check("for...of head", "for (using r of []) {}");
check("await using in sync fn", "await using r = null;");
check("await using in async fn", "await using r = null;", AsyncFunction);
check("for await head", "for await (using r of []) {}", AsyncFunction);Expected output:
parses basic
rejected no initializer: SyntaxError
rejected object destructuring: SyntaxError
parses bracket form
parses line break
rejected if body: SyntaxError
parses braced if body
rejected for...in head: SyntaxError
parses for...of head
rejected await using in sync fn: SyntaxError
parses await using in async fn
parses for await headThe two parses results for the bracket form and the line break are the traps described above. The code is valid JavaScript, but it does not declare a resource.
Exercise
A developer writes if (debug) using log = openLog(); and gets a SyntaxError. They "fix" it by writing if (debug) on one line and { using log = openLog(); } on the next, then call log.write("x") after the if statement. What happens, and how should the code be structured?
Show answer
The braced version parses, but log is scoped to that block. It is disposed as soon as the block ends, and the later log.write call throws a ReferenceError because log is not in scope. Either do all the work with log inside the braces, or declare the resource unconditionally in the outer scope, for example using log = debug ? openLog() : null;. A null value is allowed and simply skipped at disposal.
Exercise
Which of these declare a disposable resource, which are syntax errors, and which parse as something else? (1) using [conn] = pool; (2) export using cache = openCache(); in a module (3) await using s = openStream(); inside a regular function (4) for (using r = open(); i < 3; i++) {}
Show answer
(1) Parses as the assignment using[conn] = pool and declares nothing. (2) Syntax error, because using declarations cannot be exported. (3) Syntax error, because await using requires an async function, an async generator, or module top level. (4) A valid declaration. r is opened once and disposed when the loop finishes, not on every iteration.
Exercise
Why does a classic script reject using at its top level while an ES module accepts it?
Show answer
Disposal runs when the enclosing scope exits. A module body runs once and has a definite end of evaluation, so the runtime can dispose module-level resources at that point. The top-level lexical scope of a classic script is shared with later scripts and never clearly ends, so the runtime has no point at which to dispose.