WeakMap

new WeakMap([entries])
Returns: WeakMap · Updated March 13, 2026 · Map and Set
weakmap collections garbage-collection memory

WeakMap provides a way to associate data with objects without preventing those objects from being garbage collected. When an object used as a key is no longer referenced anywhere else, it and its corresponding value can be reclaimed by the garbage collector.

Syntax

new WeakMap()
new WeakMap(iterable)

Parameters

ParameterTypeDefaultDescription
iterableArrayundefinedAn array or other iterable object whose elements are key-value pairs (2-element arrays).

Examples

Basic usage

const wm = new WeakMap();

const obj = { name: 'example' };
wm.set(obj, 'some value');

console.log(wm.get(obj));
// some value

console.log(wm.has(obj));
// true

wm.delete(obj);
console.log(wm.get(obj));
// undefined

Associating private data

const privateData = new WeakMap();

class User {
  constructor(name, email) {
    this.name = name;
    privateData.set(this, { email, createdAt: new Date() });
  }
  
  getEmail() {
    return privateData.get(this)?.email;
  }
  
  getCreatedAt() {
    return privateData.get(this)?.createdAt;
  }
}

const user = new User('Alice', 'alice@example.com');
console.log(user.getEmail());
// alice@example.com

console.log(user.name);
// Alice

Using with DOM elements

const elementData = new WeakMap();

function trackClick(element) {
  const count = elementData.get(element) || 0;
  elementData.set(element, count + 1);
  console.log(`${element.tagName} clicked ${count + 1} times`);
}

// Elements can be garbage collected when removed from DOM
// and their click counts will be cleaned up automatically

Cache with automatic cleanup

const computationCache = new WeakMap();

function expensiveComputation(obj) {
  if (computationCache.has(obj)) {
    return computationCache.get(obj);
  }
  
  // Simulate expensive operation
  const result = JSON.stringify(obj);
  computationCache.set(obj, result);
  
  return result;
}

const data = { heavy: 'data' };
console.log(expensiveComputation(data));
// '{"heavy":"data"}'

// When data is no longer referenced, cache entry can be cleaned up

Object metadata storage

const timestamps = new WeakMap();

function markCreated(obj) {
  timestamps.set(obj, Date.now());
}

function getAge(obj) {
  return Date.now() - (timestamps.get(obj) || 0);
}

const item = {};
markCreated(item);

setTimeout(() => {
  console.log('Age:', getAge(item), 'ms');
}, 100);

Common Patterns

WeakMap is ideal for:

  • Private data storage — Associate private state with objects without preventing their cleanup
  • Caching — Store cached computations that should be discarded when the cached object is no longer needed
  • DOM metadata — Attach data to DOM elements without creating memory leaks

Limitations

  • Keys must be objects (not primitives)
  • Keys are not enumerable — you cannot iterate over a WeakMap
  • Cannot check size with .size property
  • Only set(), get(), has(), and delete() methods available

See Also