Skip to content

WeakMap

This lesson explains WeakMap with clear examples, use cases, and best practices so you can use modern JavaScript confidently in real projects.

ES6+ WeakMap Overview

WeakMap is an ES6 collection that stores key-value pairs where the keys must be objects. The keys are held with weak references, so they do not prevent garbage collection when no other references to those objects remain.

WeakMap is commonly used to attach private metadata to objects, cache computed values, store DOM-related data, and keep internal library state without modifying the original object or causing memory leaks.

Feature Description
Introduced In ES6 (ECMAScript 2015)
Stores Key-value pairs with object keys
Reference Type Weak references on keys
Main Methods set(), get(), has(), delete()
Iterable No — cannot loop or get size
Common Uses Private data, metadata, caching, DOM state

Basic WeakMap Example

const userMeta =
  new WeakMap();

const user = {
  id: 1,
  name: "Alex"
};

userMeta.set(user, {
  lastLogin: "2026-06-27",
  role: "admin"
});

console.log(userMeta.get(user));
console.log(userMeta.has(user));

userMeta.delete(user);

console.log(userMeta.has(user));

WeakMap lets you associate extra data with an object using the object itself as the key. Use set(), get(), has(), and delete() to manage entries.

How WeakMap Works

Each WeakMap entry links an object key to a value. Because the key reference is weak, the entry can disappear automatically when the key object is garbage collected and no longer used elsewhere in your application.

Step Description Example Syntax
Create WeakMap Initialize an empty collection. const map = new WeakMap()
Set Value Store data using an object key. map.set(user, metadata)
Get Value Read data for a specific object. map.get(user)
Check Key See whether the object has stored data. map.has(user)
Delete Entry Remove the key-value pair. map.delete(user)
Garbage Collection Unused keys may be removed automatically. No manual cleanup required

WeakMap vs Map

Feature WeakMap Map
Key Types Objects only. Any value, including primitives.
References Weak references on keys. Strong references on keys.
Garbage Collection Entries may be removed automatically. Entries stay until deleted.
Iterable No. Yes.
size Not available. Available.
Best For Object-linked metadata and private data. General key-value storage.

WeakMap Keys Must Be Objects

const cache =
  new WeakMap();

const request = {
  url: "/api/products"
};

cache.set(request, {
  status: "pending",
  startedAt: Date.now()
});

console.log(cache.get(request));

// This throws a TypeError

// cache.set("request", { status: "ok" });
// cache.set(123, { status: "ok" });

WeakMap keys must be objects such as plain objects, arrays, functions, or DOM nodes. Primitive values like strings and numbers cannot be used as keys.

Store Private Object Data

const privateData =
  new WeakMap();

function createUser(name, salary) {
  const user = { name };

  privateData.set(user, {
    salary
  });

  return user;
}

function getSalary(user) {
  return privateData.get(user)?.salary;
}

const employee =
  createUser("Alex", 85000);

console.log(employee.name);
console.log(getSalary(employee));

WeakMap is often used to simulate private fields. External code cannot easily access the WeakMap unless it holds a reference to the same map instance.

Attach Metadata to DOM Elements

const elementData =
  new WeakMap();

function bindCounter(button) {
  elementData.set(button, {
    clicks: 0
  });

  button.addEventListener("click", () => {
    const data =
      elementData.get(button);

    data.clicks += 1;

    console.log(
      `${button.textContent}: ${data.clicks} clicks`
    );
  });
}

const saveButton =
  document.querySelector("#saveButton");

bindCounter(saveButton);

WeakMap works well with DOM nodes because metadata disappears automatically when the element is removed from the document and garbage collected.

Cache Computed Values by Object

const computedCache =
  new WeakMap();

function getArea(shape) {
  if (computedCache.has(shape)) {
    return computedCache.get(shape);
  }

  const area =
    shape.width * shape.height;

  computedCache.set(shape, area);
  return area;
}

const rectangle = {
  width: 12,
  height: 8
};

console.log(getArea(rectangle));
console.log(getArea(rectangle));

Use WeakMap to cache expensive calculations tied to specific object instances without keeping unused objects alive longer than necessary.

Weak Keys and Garbage Collection

const sessionStore =
  new WeakMap();

function createSession(user) {
  sessionStore.set(user, {
    token: "abc123",
    expiresAt: Date.now() + 3600000
  });

  return user;
}

let activeUser =
  createSession({ id: 7, name: "Sam" });

console.log(
  sessionStore.get(activeUser)
);

activeUser = null;

// When the user object is garbage collected,
// its WeakMap entry can be removed automatically

Because WeakMap does not strongly retain key objects, it helps avoid memory leaks when metadata should live only as long as the related object exists.

WeakMap Methods

Method Description Example
set(key, value) Stores a value for an object key. map.set(user, data)
get(key) Returns the value for a key. map.get(user)
has(key) Checks whether a key exists. map.has(user)
delete(key) Removes a key-value pair. map.delete(user)

WeakMap Limitations

  • Keys must be objects, not primitives.
  • Has no size property.
  • Cannot iterate with for...of.
  • No forEach(), keys(), or values() methods.
  • Cannot convert entries directly to an array.
  • You must keep the object reference to read its stored value later.

Common WeakMap Use Cases

  • Storing private or internal metadata on objects.
  • Attaching state to DOM elements safely.
  • Caching computed results tied to object instances.
  • Tracking session or authentication data per user object.
  • Keeping library-internal bookkeeping hidden from consumers.
  • Preventing memory leaks in long-running applications.

WeakMap Best Practices

  • Use WeakMap when metadata should live only as long as the key object.
  • Keep the WeakMap instance private to your module when possible.
  • Prefer WeakMap over adding hidden properties directly to objects.
  • Use regular Map when you need iteration, size, or primitive keys.
  • Store structured values such as objects when multiple fields are needed.
  • Document why weak key storage is important in your design.
  • Do not rely on WeakMap for data you need to list or serialize later.

Common WeakMap Mistakes

  • Trying to use strings or numbers as WeakMap keys.
  • Expecting to loop through all entries in a WeakMap.
  • Using WeakMap when a regular Map with iteration is required.
  • Losing the object reference and then calling get().
  • Assuming WeakMap provides true language-level privacy by itself.
  • Expecting a size property to count stored entries.
  • Choosing WeakMap without understanding garbage collection behavior.

WeakMap vs WeakSet

Feature WeakMap WeakSet
Stores Key-value pairs with object keys. Objects only.
Main Question "What data belongs to this object?" "Is this object a member?"
Methods set(), get(), has(), delete() add(), has(), delete()
Best For Metadata, private fields, caching. Tagging and membership checks.

Key Takeaways

  • WeakMap is an ES6 collection for object-keyed metadata with weak references.
  • Use set(), get(), has(), and delete() to manage entries.
  • Keys must be objects, and entries may disappear through garbage collection.
  • WeakMap is ideal for private data, DOM metadata, and object-linked caching.
  • Choose Map or WeakSet when iteration, size, or simple membership is needed instead.

Pro Tip

If you need to attach extra information to an object without changing its shape, WeakMap is usually the right tool. If you only need yes-or-no membership, use WeakSet instead.