Private Data with WeakMap
Write a JavaScript function that uses WeakMap to associate private data with an object. Create a WeakMap, store a secret value keyed by an object, and retrieve it. WeakMap keys are objects (not primitives) and do not prevent garbage collection of the key object.
WeakMap is a JavaScript collection introduced in ES6 where keys are weakly referenced. If there are no other references to a key object, it can be garbage collected, and the WeakMap entry is automatically removed. This makes WeakMap ideal for storing private data associated with DOM elements, caching, and preventing memory leaks.
Unlike Map, WeakMap has no .size property and is not iterable. Its methods are limited to get(), set(), has(), and delete(). The weak referencing behavior is a JavaScript-specific feature that enables efficient memory management for object-associated data without creating memory leaks.
Time complexity is O(1) for get, set, has, and delete operations. Space complexity is O(n) for n entries, but entries are automatically cleaned up when key objects are garbage collected, preventing unbounded growth.
Edge cases include using primitives as keys (throws TypeError), checking for non-existent keys (returns undefined), overwriting existing keys, and ensuring the WeakMap does not prevent garbage collection of its keys.
Example Input & Output
Another secret
Numeric secret as string
Empty string secret
Another test
Create object key and store secret
Algorithm Flow

Solution Approach
Best Answers
function solution(secret) {
var key = {};
var wm = new WeakMap();
wm.set(key, secret);
return wm.get(key);
}Comments (0)
Join the Discussion
Share your thoughts, ask questions, or help others with this Challenge.
