JavaScript using Keyword -- Automatic Resource Cleanup
How many times have you written a try...finally block just to clean up a resource? File handles, database connections, event listeners -- the pattern is always the same: open, use, remember to close. And let's be honest, sometimes we forget.
JavaScript now has the using keyword for explicit resource management. When the variable goes out of scope, cleanup happens automatically. Chrome 123+ and Firefox 119+ stable.
The Syntax
// Before: manual cleanup
const handle = getFileHandle();
try {
await handle.write(data);
} finally {
handle.close();
}
// After: automatic cleanup
{
using handle = getFileHandle();
await handle.write(data);
} // handle.close() called automatically
How It Works
Any object with a Symbol.dispose method can be used with using. For async cleanup, use await using with Symbol.asyncDispose:
class DatabaseConnection {
[Symbol.dispose]() {
this.close();
console.log('Connection closed');
}
}
function query() {
using conn = new DatabaseConnection();
return conn.execute('SELECT * FROM users');
} // conn is automatically disposed here
Async Resources
async function processFile() {
await using file = await openFile('data.csv');
const content = await file.read();
return parse(content);
} // file is automatically closed
Browser Support
Chrome 123+ and Firefox 119+ (stable). TC39 Stage 4 -- part of the ECMAScript standard.
- No more forgotten cleanup code
- Works with sync (using) and async (await using) resources
- TC39 Stage 4 -- standardised
- Built-in DisposableStack for managing multiple resources
Happy coding!
If you want to go deeper and learn how to build real, production-ready CSS design systems step by step, check out my full course here: CSS Design Systems Course If you found this helpful, I'd love to connect! Follow me on Twitter/X @alexandersstudi or LinkedIn for more CSS and design system tips.