Hint
WeakRef: hold object without preventing GC; FinalizationRegistry: callback when object is collected
Advanced memory management APIs β use sparingly and only for performance optimizations.
// WeakRef β holds a weak reference (doesn't prevent GC)
let bigObject = { data: new Array(1_000_000).fill('*') };
const ref = new WeakRef(bigObject);
bigObject = null; // release strong reference β GC can now collect it
// Access via .deref() β returns undefined if already collected
const obj = ref.deref();
if (obj) {
console.log('Still alive:', obj.data.length);
} else {
console.log('Was garbage collected');
}
// FinalizationRegistry β callback when a registered object is collected
const registry = new FinalizationRegistry((heldValue) => {
console.log('Collected! Clean up:', heldValue);
cleanupResources(heldValue);
});
let target = { name: 'Alice' };
registry.register(target, 'alice-cleanup-token');
// target can now be GC'd β callback fires sometime after
Important: GC timing is non-deterministic. Don't use these for program correctness β only for optional caching or cleanup of non-critical resources.