Code Logo

Private Data with WeakMap

Published at25 Jul 2026
JavaScript Data Structures Hard 0 views
Like0

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

Example 1
Input
"hello"
Output
hello
Explanation

Another secret

Example 2
Input
"42"
Output
42
Explanation

Numeric secret as string

Example 3
Input
""
Output
Explanation

Empty string secret

Example 4
Input
"data"
Output
data
Explanation

Another test

Example 5
Input
"secret123"
Output
secret123
Explanation

Create object key and store secret

Algorithm Flow

Recommendation Algorithm Flow for Private Data with WeakMap
Recommendation Algorithm Flow for Private Data with WeakMap

Solution Approach

function solution(key, secret) {
  var wm = new WeakMap();
  wm.set(key, secret);
  return wm.get(key);
}

Best Answers

javascript - Approach 1
function solution(secret) {
  var key = {};
  var wm = new WeakMap();
  wm.set(key, secret);
  return wm.get(key);
}