Stop Nesting try/finally for Cleanup. JavaScript Has using
TL;DR: using file = ... calls file[Symbol.dispose]() the moment the block ends, whether it returned or threw. It ships in Chrome 134+, Edge 134+, Firefox 141+, Node 24+, Deno and Bun, but Safari has it only in Technology Preview, so it is not Baseline yet. The pyramid nobody wants to touch Every codebase has a function shaped like this: const file = await open ( path , " w " ); try { const timer…
The use of `try/finally` blocks for resource cleanup in JavaScript can lead to cluttered code with multiple levels of indentation and potential leaks. In response to this issue, JavaScript now supports the `using` keyword, which simplifies resource management by calling the `Symbol.dispose()` method when a scope exits. This feature is available in modern browsers, Node, Deno, and Bun, although Safari still has it in a Technology Preview stage.
The `using` keyword adds two declarations and a few helpers, allowing object with a `[Symbol.dispose()]` method to be easily managed. By using `using`, developers can avoid writing repetitive `try/finally` blocks and ensure that resources are properly released in the reverse order they were acquired. This approach eliminates the risk of forgetting to include a `finally` block and can help prevent resource leaks, which can be particularly problematic in production environments. The TC39 proposal for `using` is currently in Stage 4 and is expected to be published in 2027.
Written by urgent.news from Dev.to's reporting — not their text. Machine-written — may contain errors; check the original before relying on it.