Memory Management & Garbage Collection
How do WeakMap and WeakSet help with memory management?
WeakMap and WeakSet help with memory management by not preventing garbage collection of their keys: 1) They hold 'weak' references to their keys, unlike Map and Set which hold strong references, 2) If a key object in a WeakMap has no other references, it can be garbage collected along with its associated value, 3) This prevents memory leaks in scenarios where you want to associate data with objects without affecting their lifecycle, 4) WeakMap is particularly useful for storing private or metadata about objects, 5) WeakSet is useful for keeping track of objects without preventing their garbage collection, 6) They cannot be iterated over since keys could disappear at any time during garbage collection, 7) They're ideal for implementing caches or mappings that shouldn't interfere with memory management, 8) Neither WeakMap nor WeakSet accept primitive values as keys, since primitives are not held by reference.