Codectionary / Developer documentation / JavaScript

WeakMap and WeakSet

WeakMap and WeakSet are like Map and Set, but their keys (WeakMap) or values (WeakSet) must be objects, and those references are "weak" - meaning they do not prevent the object from being garbage collected if nothing else references it. This makes them ideal for attaching metadata to objects without causing memory leaks.

Syntax

const wm = new WeakMap();
wm.set(objectKey, value);

Examples

WeakMap for Private Object Metadata

Associating extra data with an object without modifying the object itself or leaking memory.

const privateData = new WeakMap();

class User {
  constructor(name) {
    privateData.set(this, { loginAttempts: 0 });
    this.name = name;
  }

  recordLoginAttempt() {
    const data = privateData.get(this);
    data.loginAttempts++;
    return data.loginAttempts;
  }
}

const user = new User("Alice");
console.log(user.recordLoginAttempt()); // 1
// If "user" is later garbage collected, its entry in privateData is automatically cleaned up too

WeakSet for Tracking Object Membership

Tracking which objects have been "seen" or processed, without preventing cleanup.

const processedItems = new WeakSet();

function processItem(item) {
  if (processedItems.has(item)) {
    console.log("Already processed, skipping");
    return;
  }
  processedItems.add(item);
  console.log("Processing item...");
}

const obj = { id: 1 };
processItem(obj); // "Processing item..."
processItem(obj); // "Already processed, skipping"

Best practices

  • Use WeakMap when attaching metadata to objects you do not own or control the lifecycle of, so it does not prevent garbage collection
  • Remember WeakMap/WeakSet are not iterable and have no size property - they intentionally hide their contents since entries can disappear at any time via garbage collection
  • Only use object references as keys (WeakMap) or values (WeakSet) - primitives like strings or numbers are not allowed
  • Reach for a regular Map when you need to iterate over entries or know how many there are - WeakMap is specifically for the memory-safe metadata use case

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation