Skip to main content

IndexWeb PlatformTutorial

JavaScript using Keyword: Explicit Resource Management Guide

Build a CSV-to-SQLite importer in Node 24 with using, await using and DisposableStack. Error rules, TypeScript setup and gotchas, every output run and checked.

By LearnWebCraft Team25 min readIntermediate

Here's a bug that takes one missing line to ship and an afternoon to find.

You have a small script that imports a CSV export into SQLite every night. Most nights it's fine. On a night when the export has a bad row, the script throws, a wrapper catches the error and logs it, and then the next job that touches the database waits on a lock and fails with database is locked. The import opened a transaction with BEGIN, threw halfway through, and never reached the ROLLBACK. The connection is still open too, because the db.close() call sits at the bottom of the function, after the code that threw.

The fix is a try/finally. It always is. The problem is that by the time you have a file handle, a database connection, a prepared statement and a transaction, you have four things to clean up in the right order, and the try/finally version of that code is ugly enough that people skip it.

JavaScript now has a proper answer to this. It's called explicit resource management, and it gives you two new declarations, using and await using, that clean up a value automatically when the block that declared it ends. No matter how the block ends: normal exit, return, break, or a thrown error.

In this tutorial we'll rebuild that nightly importer with using, watch it roll back on bad data, and then go through the parts that are easy to get wrong: error handling when cleanup itself fails, DisposableStack for resources you collect conditionally, the TypeScript settings you need, and a handful of gotchas I hit while writing this. All code was run on Node.js 24.22, and the output blocks are copied from the terminal.

What you need to follow along

You need Node.js 24 or newer. Node 24 ships V8 13.6, which has using, await using, DisposableStack and AsyncDisposableStack turned on by default. You can check that your runtime has them with one line:

Fig. 1bash
node -e "console.log(typeof Symbol.dispose, typeof DisposableStack, typeof SuppressedError)"

On Node 24.22 that prints:

Fig. 2txt
symbol function function

We'll also use node:sqlite, the SQLite module built into Node, so there's nothing to install. Make a folder, put the files from this guide in it as .mjs files, and run them with node file.mjs.

Where the feature stands in late 2026

Before we write code, a quick reality check on support, because this decides whether you can use it in browser code today or only on the server.

The proposal is Explicit Resource Management, championed by Ron Buckton (who also did much of the TypeScript work). It has reached Stage 4, and TC39's list of finished proposals gives 2027 as its expected publication year, so it will appear in the ECMAScript 2027 spec. You will see blog posts calling it an ES2026 feature. That's not quite right, but it doesn't matter much in practice, because engines shipped it long before the paperwork.

Here is what MDN's browser compatibility data lists for DisposableStack, which tracks the same rollout as the syntax:

Runtime First version with support
Chrome and Edge 134
Firefox 141
Safari (macOS and iOS) 27.3
Node.js 24.0.0
Deno 2.2.10
Bun 1.3.0

Safari was the last engine to land it. WebKit shipped full support in Safari Technology Preview 250 in August 2026, and TechTimes covered it as the end of the last cross-browser gap. MDN still marks the feature as "limited availability" rather than Baseline, because plenty of real users are on older iPhones that haven't updated. So my rule of thumb is simple. On the server (Node 24, Deno, Bun), use it today. In browser code, either compile it with TypeScript or Babel, or wait until your analytics say the old Safari versions are gone.

The problem, written the old way

Here's what that importer looks like once it's fixed with try/finally, the way you'd write it without the new syntax:

Fig. 3js
import { DatabaseSync } from 'node:sqlite';
import { open } from 'node:fs/promises';

async function importOrders(csvPath, dbPath) {
  const file = await open(csvPath);
  try {
    const db = new DatabaseSync(dbPath);
    try {
      db.exec('BEGIN');
      let committed = false;
      try {
        const insert = db.prepare('INSERT INTO orders VALUES (?, ?, ?)');
        // ... read lines, insert rows ...
        db.exec('COMMIT');
        committed = true;
      } finally {
        if (!committed) db.exec('ROLLBACK');
      }
    } finally {
      db.close();
    }
  } finally {
    await file.close();
  }
}

Three levels of nesting for three resources. The actual work, reading lines and inserting rows, is buried in the middle. And this version still has a subtle problem: if db.close() throws inside a finally while an error from the import is already on its way out, the original error is lost. JavaScript throws the newer one and drops the older one on the floor. You find out about the cleanup failure and never learn what actually went wrong.

Keep that in mind. using fixes the nesting, and it also fixes the lost error.

Step 1: the dispose protocol

The whole feature rests on one well-known symbol. Any object with a method under Symbol.dispose is a "disposable". When you declare it with using, JavaScript calls that method when the enclosing block exits.

Fig. 4js
{
  using a = { [Symbol.dispose]() { console.log('dispose a'); } };
  using b = { [Symbol.dispose]() { console.log('dispose b'); } };
  console.log('body');
}

Output:

Fig. 5txt
body
dispose b
dispose a

Two things to notice. First, the dispose methods ran after the body, at the closing brace, without any call from us. Second, they ran in reverse order. b was declared last, so it was disposed first. This is the same order you'd get from nested try/finally blocks, and it's the order you almost always want: if b depends on a (a statement depends on a database, a database lives in a temp folder), b must close before a does.

For async cleanup there's a second symbol, Symbol.asyncDispose, and a second declaration, await using. The block waits for each async disposer to finish before moving on. If a value only has a sync Symbol.dispose, await using falls back to it, which I checked:

Fig. 6js
const res = (n) => ({ n, [Symbol.dispose]() { console.log('closed', n); } });

{
  await using s = res('sync-only');
  console.log('await using with sync disposer ok');
}
Fig. 7txt
await using with sync disposer ok
closed sync-only

The reverse doesn't work, and that's one of the gotchas we'll see later.

A few more rules from MDN's using reference that are worth having in your head early:

A using binding behaves like const. You must initialize it and you can't reassign it. The value must be an object with a callable [Symbol.dispose], or null, or undefined. null and undefined are allowed on purpose, so that "maybe I have a resource" doesn't need an if. They're skipped at disposal time.

The dispose method is looked up when the declaration runs, not when the block ends. If you assign a non-function to Symbol.dispose, you get a TypeError immediately, on the using line, instead of a surprise later.

Step 2: build the importer

Now the real thing. We'll write the nightly importer from the opening story, using node:sqlite and a file handle from node:fs/promises. Start with a CSV file called orders.csv that has a bad row on purpose:

Fig. 8txt
id,customer,total
1,Asha,42.50
2,Ben,19.99
3,Chloe,not-a-number
4,Dev,7.25

A disposable transaction

SQLite connections and statements in Node 24 already implement Symbol.dispose. Transactions don't, because a transaction isn't an object in node:sqlite, it's just BEGIN and COMMIT strings. So we write a small wrapper. Save this as transaction.mjs:

Fig. 9js
export function transaction(db) {
  db.exec('BEGIN');
  let committed = false;
  return {
    commit() {
      db.exec('COMMIT');
      committed = true;
    },
    [Symbol.dispose]() {
      if (!committed) {
        db.exec('ROLLBACK');
        console.log('  rolled back');
      }
    },
  };
}

This is the pattern I reach for most often with using. The disposer doesn't mean "close"; it means "undo whatever I didn't explicitly finish". If the code reaches commit(), disposal does nothing. If anything throws before that, disposal rolls back. You get the safe behavior by default, and you have to opt in to the permanent one.

The import function

Save this as import.mjs:

Fig. 10js
import { DatabaseSync } from 'node:sqlite';
import { open } from 'node:fs/promises';
import { transaction } from './transaction.mjs';

async function importOrders(csvPath, dbPath) {
  await using file = await open(csvPath);
  using db = new DatabaseSync(dbPath);
  db.exec('CREATE TABLE IF NOT EXISTS orders (id INTEGER PRIMARY KEY, customer TEXT, total REAL)');

  using tx = transaction(db);
  using insert = db.prepare('INSERT INTO orders VALUES (?, ?, ?)');

  let line = 0;
  for await (const row of file.readLines()) {
    if (line++ === 0) continue; // header
    const [id, customer, total] = row.split(',');
    const amount = Number(total);
    if (Number.isNaN(amount)) throw new Error(`Bad total on line ${line}: "${total}"`);
    insert.run(Number(id), customer, amount);
  }
  tx.commit();
  return line - 1;
}

try {
  const n = await importOrders(process.argv[2], 'orders.db');
  console.log(`imported ${n} rows`);
} catch (err) {
  console.error('import failed:', err.message);
}

using db = new DatabaseSync('orders.db');
console.log('rows in table:', db.prepare('SELECT count(*) AS n FROM orders').get().n);

Compare the body of importOrders with the nested version above. Four resources, zero nesting, and the cleanup order is still correct: the statement is finalized first, then the transaction is rolled back or left alone, then the database closes, then the file handle closes.

Notice the two different declarations. The file handle uses await using, because closing a FileHandle is asynchronous and it implements Symbol.asyncDispose. The database and the statement use plain using, because node:sqlite is a synchronous API and they implement Symbol.dispose.

Also notice the last two lines. A using declaration at the top level of an ES module is allowed, and the database closes when the module finishes evaluating.

Run it with the bad row

Fig. 11bash
node import.mjs orders.csv
Fig. 12txt
  rolled back
import failed: Bad total on line 4: "not-a-number"
rows in table: 0

This is exactly the behavior the script in the opening story lacked. Row 3 is bad, the function throws, and on the way out the transaction rolls back, so rows 1 and 2 are not left half-imported. The database connection is closed, the file handle is closed, and the next query against the same file runs fine instead of hanging on a lock.

Fix the data and run it again

Change not-a-number to 12.00 and rerun:

Fig. 13txt
imported 4 rows
rows in table: 4

commit() ran, so the transaction disposer did nothing. Everything else closed the same way it did in the failure case. That's the property I care about most: the success path and the failure path share the same cleanup code, so the cleanup code gets tested every time the script runs, not only on the rare bad night.

Step 3: what happens when cleanup itself fails

Remember the lost-error problem with nested finally blocks. Here's how using handles it. I wrote two resources whose disposers both throw, inside a block whose body throws as well:

Fig. 14js
const noisy = (name) => ({
  [Symbol.dispose]() {
    console.log('disposing', name);
    throw new Error(name + ' dispose failed');
  },
});

try {
  using a = noisy('a');
  using b = noisy('b');
  throw new Error('body failed');
} catch (e) {
  console.log(e.name);
  console.log('error:', e.error.message);
  console.log('suppressed:', e.suppressed.name, '->', e.suppressed.error.message);
  console.log('inner:', e.suppressed.suppressed.message);
}
Fig. 15txt
disposing b
disposing a
SuppressedError
error: a dispose failed
suppressed: SuppressedError -> b dispose failed
inner: body failed

Three facts fall out of this.

Every disposer ran. b's disposer threw, and a's disposer still ran afterwards. One broken cleanup doesn't stop the others, which is the opposite of what a hand-written sequence of close() calls does.

Nothing was lost. The new SuppressedError type has two properties. error is the newer error, and suppressed is the older one it replaced. Errors are wrapped in the order they happened, so you get a chain: the outermost error is the last disposer failure, and if you walk down suppressed you eventually reach the original body failed.

The original error is at the bottom of the chain, which is a bit awkward to read. If you log errors centrally, it's worth a small helper that unwraps the chain so the root cause appears first:

Fig. 16js
function rootCause(err) {
  while (err instanceof SuppressedError) err = err.suppressed;
  return err;
}

When only the body throws and every disposer succeeds, you get the body's error unchanged, not wrapped in anything. SuppressedError only appears when there is more than one failure to report. In the importer above, the rolled-back run threw a plain Error, which is why err.message printed the line number directly.

Step 4: DisposableStack for resources you collect as you go

using is great when you know your resources up front and they all live for exactly one block. Two situations don't fit that shape:

  1. You open resources conditionally or in a loop, so you can't write one using line per resource.
  2. You build an object that owns several resources and must outlive the function that created it, such as a class with an async factory.

For both, there's DisposableStack (and its async twin, AsyncDisposableStack). It's a container of cleanup work that is itself disposable. MDN's reference lists the methods; here's what each one is for, in the order I use them:

Method What it does
use(value) Registers something that already has Symbol.dispose. Returns the value.
adopt(value, fn) Registers something that isn't disposable, with a cleanup function to call on it.
defer(fn) Registers a plain callback to run at disposal.
move() Transfers everything to a new stack and marks this one as disposed, without running anything.
dispose() Runs everything in reverse order. On the async stack this is disposeAsync().
disposed Read-only flag that tells you whether the stack has been disposed.

A quick tour:

Fig. 17js
const stack = new DisposableStack();
stack.defer(() => console.log('deferred 1'));
stack.adopt(42, (v) => console.log('adopted value', v));
console.log('disposed?', stack.disposed);
stack.dispose();
console.log('disposed?', stack.disposed);
stack.dispose(); // second call is a no-op

try {
  stack.defer(() => {});
} catch (e) {
  console.log(e.constructor.name + ':', e.message);
}
Fig. 18txt
disposed? false
adopted value 42
deferred 1
disposed? true
ReferenceError: Cannot call DisposableStack.prototype.defer on an already-disposed DisposableStack

Disposing twice is safe, but adding to a disposed stack throws. Note that it's a ReferenceError in V8, which surprised me. I expected a TypeError.

On Node 24 the async stack's methods are use, adopt, defer, move, disposeAsync and disposed. I'm pointing that out because some articles write dispose() for the async version, and that method doesn't exist on it.

The move() pattern: safe constructors

This is the one pattern I'd learn even if you skip everything else in this section. Say you want a ReportWriter that opens the database and an output file, and keeps both open until the caller is done with it. The tricky part is the constructor. If the database opens fine and then the output file fails to open, you must close the database before throwing, or you've leaked it. The caller never got an object, so they can't clean it up.

Here's the factory with AsyncDisposableStack and move():

Fig. 19js
import { DatabaseSync } from 'node:sqlite';
import { open } from 'node:fs/promises';

class ReportWriter {
  #stack;

  constructor(db, out) {
    this.db = db;
    this.out = out;
  }

  static async create(dbPath, outPath) {
    await using stack = new AsyncDisposableStack();
    const db = stack.use(new DatabaseSync(dbPath));
    const out = stack.use(await open(outPath, 'w'));

    const writer = new ReportWriter(db, out);
    writer.#stack = stack.move();
    return writer;
  }

  async write() {
    const rows = this.db.prepare('SELECT customer, total FROM orders').all();
    for (const r of rows) await this.out.write(`${r.customer}\t${r.total}\n`);
    return rows.length;
  }

  async [Symbol.asyncDispose]() {
    await this.#stack.disposeAsync();
    console.log('writer closed');
  }
}

Read create carefully, because the trick is in the last three lines. The local stack is declared with await using, so if anything throws before the end, the stack disposes and closes whatever was already opened. If we get all the way to stack.move(), the resources are transferred to a fresh stack owned by the writer, and the local stack is marked disposed. When the function returns and the local await using fires, it finds an empty, already-disposed stack and does nothing.

So the function has two outcomes, and both are clean: either you get a fully built writer that owns its resources, or you get an exception and nothing is left open. Using it:

Fig. 20js
{
  await using w = await ReportWriter.create('orders.db', 'report.tsv');
  console.log('wrote', await w.write(), 'rows');
}

try {
  await using w = await ReportWriter.create('orders.db', 'no/such/dir/report.tsv');
} catch (e) {
  console.log('create failed:', e.code);
}
Fig. 21txt
wrote 4 rows
writer closed
create failed: ENOENT

I wanted proof that the failure case really closed the database rather than taking it on faith, so I kept a reference to the connection outside the stack and checked isOpen, which DatabaseSync exposes:

Fig. 22js
let leaked;
try {
  await using stack = new AsyncDisposableStack();
  leaked = stack.use(new DatabaseSync(':memory:'));
  stack.use(await open('no/such/dir/x', 'w'));
} catch (e) {
  console.log(e.code, 'db still open?', leaked.isOpen);
}
Fig. 23txt
ENOENT db still open? false

The database was closed before the error reached the catch. Without the stack, that connection would have stayed open until garbage collection, which for SQLite can mean a held file lock.

Step 5: what's already disposable in Node 24

You don't have to wrap everything yourself. I went through the Node APIs I use most and checked which ones implement the protocol on Node 24.22:

Fig. 24js
import { DatabaseSync } from 'node:sqlite';
import fsp from 'node:fs/promises';
import { createServer } from 'node:http';

const db = new DatabaseSync(':memory:');
console.log('DatabaseSync dispose', typeof db[Symbol.dispose]);
console.log('StatementSync dispose', typeof db.prepare('select 1')[Symbol.dispose]);
console.log('mkdtempDisposable', typeof fsp.mkdtempDisposable);
const t = setTimeout(() => {}, 1);
console.log('Timeout dispose', typeof t[Symbol.dispose]);
const ac = new AbortController();
console.log('AbortController dispose', typeof ac[Symbol.dispose]);
const dir = await fsp.opendir('.');
console.log('Dir asyncDispose', typeof dir[Symbol.asyncDispose]);
console.log('http server asyncDispose', typeof createServer()[Symbol.asyncDispose]);
Fig. 25txt
DatabaseSync dispose function
StatementSync dispose function
mkdtempDisposable function
Timeout dispose function
AbortController dispose undefined
Dir asyncDispose function
http server asyncDispose function

FileHandle, Dir, the HTTP server, worker threads, timers and SQLite objects all work with using or await using out of the box. AbortController does not, which is a shame, because "abort when I leave this scope" is a natural use. You can bridge it with a stack: stack.adopt(new AbortController(), (c) => c.abort()).

Temporary directories that delete themselves

My favorite one on that list is fsPromises.mkdtempDisposable(). It creates a temp directory and returns an object whose async disposer deletes the directory and everything in it. This replaces a whole category of test-cleanup code:

Fig. 26js
import { mkdtempDisposable, writeFile, readdir } from 'node:fs/promises';
import { tmpdir } from 'node:os';
import { join } from 'node:path';

let path;
{
  await using tmp = await mkdtempDisposable(join(tmpdir(), 'erm-'));
  path = tmp.path;
  await writeFile(join(tmp.path, 'a.txt'), 'hi');
  console.log('inside:', await readdir(tmp.path));
}

try {
  await readdir(path);
} catch (e) {
  console.log('after block:', e.code);
}
Fig. 27txt
inside: [ 'a.txt' ]
after block: ENOENT

Note that the returned object isn't a string. The directory path is on .path.

Timers and iterators

A timer declared with using is cleared when the block ends. This block prints nothing, because the timeout is cancelled before it fires:

Fig. 28js
{
  using t = setTimeout(() => console.log('SHOULD NOT PRINT'), 10);
}

Iterators are disposable too, and disposing one calls its return() method. That's the same thing for...of does when you break, and it means a generator's finally block runs even if you stop pulling values early:

Fig. 29js
function* g() {
  try { yield 1; yield 2; }
  finally { console.log('generator cleaned up'); }
}

{
  using it = g();
  console.log(it.next().value);
}
Fig. 30txt
1
generator cleaned up

You can also put using in a for...of head. Each value is disposed at the end of its own iteration, not at the end of the loop:

Fig. 31js
const res = (n) => ({ n, [Symbol.dispose]() { console.log('closed', n); } });
for (using r of [res(1), res(2)]) console.log('using', r.n);
Fig. 32txt
using 1
closed 1
using 2
closed 2

Step 6: the gotchas

These are the mistakes I made, or nearly made, while building the examples above.

Using using on something that only has async cleanup

FileHandle has Symbol.asyncDispose but no Symbol.dispose. If you forget the await on the declaration, you don't get a warning at the end of the block. You get an error right away:

Fig. 33js
const fh = await open('t3.mjs');
try {
  using bad = fh;
} catch (e) {
  console.log(e.constructor.name + ':', e.message);
}
Fig. 34txt
TypeError: Symbol(Symbol.dispose) is not a function

The error message doesn't mention await using, which makes it more confusing than it needs to be. If you see this message, check whether the value you're declaring needs await using. Also note the two separate awaits in await using file = await open(path). The second one waits for the file to open. The first one marks the binding for async disposal. You need both.

Returning a resource you declared with using

using means "this resource belongs to this block". If you return it, the caller gets an object that was already disposed:

Fig. 35js
function openLog() {
  using res = { closed: false, [Symbol.dispose]() { this.closed = true; } };
  return res;
}
console.log('returned resource closed?', openLog().closed);
Fig. 36txt
returned resource closed? true

There's no error and no warning, just a closed resource in the caller's hands. Use const for anything you hand back, or use the move() pattern from Step 4 if you need cleanup on the failure path.

No destructuring

You can't destructure in a using declaration. The disposable is the whole object, so pulling out properties would leave nothing to dispose. V8's error for this is not friendly:

Fig. 37js
{ using { a } = { a: 1, [Symbol.dispose]() {} } }
Fig. 38txt
SyntaxError: Unexpected token '{'

Declare the whole object with using, then destructure from it on the next line.

Top-level scripts and switch cases

MDN lists the places where using is not allowed. The ones you're likely to hit are the top level of a classic script (not a module), because script-level variables live forever and would never be disposed, and directly inside a case clause of a switch without a block around it. Add braces around the case body and it works.

One thing I tested because I wasn't sure: a CommonJS file in Node is fine. A .cjs file with using x = null; at the top runs, because Node wraps CommonJS modules in a function, so the "top level" is really a function body.

It isn't a replacement for every try/finally

using ties cleanup to a block. If your cleanup doesn't belong to a block, it doesn't fit. A WebSocket that stays open for the lifetime of a page, a cache that's cleared on a timer, a subscription that ends when a user clicks a button: these have no natural closing brace, and forcing them into using makes the code harder to follow, not easier.

Step 7: TypeScript setup

TypeScript has supported the syntax since 5.2 (see the TypeScript 5.2 release notes), but you need the right lib setting, and you need to know what downleveling does. I tested with TypeScript 6.0.3, which is what this site's repo uses, on this file:

Fig. 39ts
class Lock implements Disposable {
  [Symbol.dispose]() { console.log('released'); }
}

export function run() {
  using l = new Lock();
  console.log('working');
}

With "lib": ["es2022"] the compiler doesn't know about any of the new types:

Fig. 40txt
error TS2318: Cannot find global type 'Disposable'.
a.ts(1,23): error TS2304: Cannot find name 'Disposable'.
a.ts(2,11): error TS2550: Property 'dispose' does not exist on type 'SymbolConstructor'. Do you need to change your target library? Try changing the 'lib' compiler option to 'esnext' or later.

The fix is to add esnext.disposable to lib, or to use esnext:

Fig. 41json
{
  "compilerOptions": {
    "target": "es2022",
    "lib": ["es2022", "esnext.disposable", "dom"]
  }
}

Now the important part. With target below esnext, TypeScript rewrites using into helper functions called __addDisposableResource and __disposeResources. The output works, but the helpers still read Symbol.dispose at runtime. Here's a line from the generated code:

Fig. 42js
if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined.");

So downleveling the syntax isn't enough for older runtimes. You also need the symbols, and DisposableStack if you use it, from a polyfill such as core-js. If you only need the symbols, a two-line shim at your app's entry point does it:

Fig. 43js
Symbol.dispose ??= Symbol('Symbol.dispose');
Symbol.asyncDispose ??= Symbol('Symbol.asyncDispose');

With "target": "esnext", TypeScript leaves using in the output as written, which is what you want when you're only targeting Node 24 or newer.

If you've moved to TypeScript 7, nothing changes here. The new compiler is a port of the same checker, as we covered in TypeScript 7 in Practice.

Step 8: using it in browser code

Node gets most of the attention for this feature because servers are full of handles and connections. The browser has its own version of the problem, though: event listeners, observers, intervals and object URLs that you set up together and must tear down together.

DisposableStack is a good fit for a React effect, where the cleanup function has to undo everything the effect did:

Fig. 44jsx
import { useEffect } from 'react';

function useStickyHeader(ref) {
  useEffect(() => {
    const stack = new DisposableStack();

    const onScroll = () => {
      ref.current?.classList.toggle('is-stuck', window.scrollY > 40);
    };
    window.addEventListener('scroll', onScroll, { passive: true });
    stack.defer(() => window.removeEventListener('scroll', onScroll));

    const observer = stack.adopt(
      new ResizeObserver(() => onScroll()),
      (o) => o.disconnect(),
    );
    if (ref.current) observer.observe(ref.current);

    return () => stack.dispose();
  }, [ref]);
}

Every setup line sits right next to its teardown, so when someone adds a third listener next year, the cleanup is impossible to forget. The effect's return value becomes one call. This is not React-specific; the same shape works for a Web Component's connectedCallback and disconnectedCallback, or a Vue onMounted and onUnmounted pair.

Two caveats for browser code. First, check the support table above. If you need to support Safari versions older than 27.3, compile with TypeScript or Babel and include the polyfill. Second, don't expect using to clean up anything when the user closes the tab. Disposal is tied to blocks of code finishing, and a closed tab doesn't finish anything. It just stops.

A short checklist

When I review code that uses this feature, these are the things I look at:

  1. Does every async resource use await using (or AsyncDisposableStack) and not plain using?
  2. Is anything declared with using also returned or stored somewhere that outlives the block?
  3. Do disposers that "undo" work (like the transaction) check whether the work was completed first?
  4. Is there a constructor or factory that opens more than one resource? If so, does it use the move() pattern?
  5. Does the error logging unwrap SuppressedError so the root cause is visible?
  6. For browser code or older runtimes, is there a polyfill for Symbol.dispose and DisposableStack?

Wrapping up

I didn't expect a new keyword to change how I write Node scripts this much. The importer we built has no nested blocks, its rollback runs on every failure, and any cleanup errors it hits are reported instead of swallowed. The try/finally version is the kind of code I'd be nervous about. This one I'd stop thinking about after the first review.

If you want to try this today, start small. Find one function in your project with a try/finally that closes something, rewrite it with using, and run its tests. Then look for a factory that opens two things and give it a DisposableStack. That second change is where most of the real bugs are hiding.

For more on modern JavaScript built into the platform, the Temporal API tutorial covers the other big language addition of the last couple of years, and the View Transitions API guide covers a browser API that's now usable everywhere.

Further reading

Frequently asked questions

Is using the same as C#'s using or Python's with?

Close. It's most like C#'s using declaration, which also disposes at the end of the enclosing scope. Python's with is a block statement with its own indentation, while JavaScript's using is a declaration that attaches to whatever block it's already in. Java's try-with-resources is the other close relative.

Does using replace try/finally completely?

No. It replaces the specific case of "clean this up when this block ends". You still need try/catch to handle errors, and finally is still the right tool for cleanup that isn't tied to a single object, like resetting a flag.

Can I use using with an object that doesn't have Symbol.dispose?

Not directly; you'll get a TypeError on the declaration line. Wrap it with DisposableStack.prototype.adopt(value, cleanupFn), or write a small object with a [Symbol.dispose] method like the transaction wrapper in Step 2.

What happens if I call dispose() myself and then the block ends?

The disposer runs again. JavaScript doesn't track whether you've already cleaned up. Built-ins like DisposableStack and Node's file handles make a second call a no-op, but your own disposers should do the same, usually with a flag, if they might be called twice.