Resource management

2 snippets across 2 stacks - JavaScript, Python

JSJavaScript

Explicit Resource Management (using)

JS · Modern Features
Syntax
using resource = acquireResource();
await using resource = acquireAsyncResource();
Example
class TempFile {
  constructor(path) {
    this.path = path;
    console.log(`Created: ${path}`);
  }

  [Symbol.dispose]() {
    console.log(`Cleaned up: ${this.path}`);
  }
}

{
  using file = new TempFile("/tmp/data.txt");
  // Use file here...
} // Automatically calls file[Symbol.dispose]() when block exits
Output
"Created: /tmp/data.txt"
"Cleaned up: /tmp/data.txt"

Note TC39 Stage 3 (expected in ES2025/2026). Similar to Python's 'with' or C#'s 'using'. Guarantees cleanup even if an error is thrown. Use Symbol.asyncDispose for async cleanup.

PYPython

Context Managers (with Statement)

PY · File I/O
Syntax
with expression as variable:
    ...
Example
from contextlib import contextmanager

@contextmanager
def temp_directory():
    import tempfile, shutil
    path = tempfile.mkdtemp()
    try:
        yield path
    finally:
        shutil.rmtree(path)

with temp_directory() as tmp:
    print(f"Working in {tmp}")

Note The with statement guarantees cleanup code runs even if an exception occurs. Use contextlib.contextmanager to build custom context managers from generators.

Frequently asked questions

How does JavaScript handle resource management?
This task is covered in 2 stacks on this page: JavaScript, Python. The "Explicit Resource Management (using)" snippet in JavaScript uses `using resource = acquireResource();`.
Which code does the JavaScript example use?
The "Explicit Resource Management (using)" snippet uses `using resource = acquireResource();`, from the Modern Features section of the JavaScript cheat sheet.
Which stacks cover "resource management" on this page?
JavaScript, Python. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Explicit Resource Management (using)": TC39 Stage 3 (expected in ES2025/2026). Similar to Python's 'with' or C#'s 'using'. Guarantees cleanup even if an error is thrown. Use Symbol.asyncDispose for async cleanup.