🟑 MediumModern JSπŸ“– Theory Question

What are WeakRef and FinalizationRegistry?

πŸ’‘

Hint

WeakRef: hold object without preventing GC; FinalizationRegistry: callback when object is collected

Full Answer

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.

πŸ’‘ WeakRef + FinalizationRegistry are for library authors building caches that should automatically clean up. App code rarely needs these β€” use WeakMap instead.

More Modern JS Questions

🟑 MediumWhat are generators and when would you use them?β†’πŸŸ’ EasyWhat is optional chaining (?.) and nullish coalescing (??)?β†’πŸŸ’ EasyWhat are tagged template literals and what are they used for?β†’πŸŸ’ EasyExplain destructuring for objects and arrays β€” including defaults, renaming, rest, and nesting.β†’

Practice this in a timed sprint β†’

5 free questions, no signup required

⚑ Start Sprint