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.