JavaScript Interview Question #129

What are WeakMap and WeakSet?

Generators, Browser Storage, Security & Advanced Runtime Concepts Senior Advanced

Quick Interview Answer

WeakMap stores key-value associations where keys must be objects or non-registered symbols supported by the environment, and those keys are held weakly. WeakSet similarly stores weakly held eligible values.

Detailed Explanation

WeakMap stores key-value associations where keys must be objects or non-registered symbols supported by the environment, and those keys are held weakly. WeakSet similarly stores weakly held eligible values.

Weak collections do not prevent their object entries from being garbage-collected when no other strong references remain. They are intentionally not enumerable because garbage collection timing is not deterministic. WeakMap is useful for metadata associated with object lifetimes.

Code Example

const privateData = new WeakMap();

let user = { name: "Asif" };

privateData.set(user, {
    lastLogin: new Date()
});

console.log(privateData.get(user));

user = null;
// The original object may later be garbage-collected.