It seems like you are using an ad blocker. To enhance your experience and support our website, please consider:

  1. Signing in to disable ads on our site.
  2. Sign up if you don't have an account yet.
  3. Or, disable your ad blocker by doing this:
    • Click on the ad blocker icon in your browser's toolbar.
    • Select "Pause on this site" or a similar option for lancecourse.com.

Javascript in 100 bits

Course by zooboole,

Last Updated on 2025-01-28 08:04:00

Lesson 83 - WeakMaps in JavaScript

What is a WeakMap?

A WeakMap is similar to a Map but with some differences that make it more suitable for storing data tied to object lifecycles. Keys in a WeakMap must be objects, and they are held "weakly," meaning if there are no other references to the object, it can be garbage collected.

Key Differences from Map

Feature Map WeakMap
Key types Any Only objects
Iterability Yes No
Size property Yes (.size) No
Garbage Collection safe No Yes (weakly held references)

Creating a WeakMap

const weakMap = new WeakMap();
let user = { name: "Jane" };
weakMap.set(user, "Active");
console.log(weakMap.get(user)); // Active

Note: If the user object is no longer referenced elsewhere, it will be garbage collected, and the WeakMap entry will disappear automatically.

Valid Usage

const wm = new WeakMap();

const obj1 = {};
const obj2 = {};

wm.set(obj1, "Data for obj1");
wm.set(obj2, "Data for obj2");

console.log(wm.has(obj1)); // true
wm.delete(obj2);           // removes obj2 from the WeakMap

Invalid Usage

const wm = new WeakMap();
wm.set("name", "Lance"); //  Error: keys must be objects

Use Cases

  • Private data for class instances
  • Caching or memoization tied to object references
  • Event listeners or DOM nodes storage without memory leaks

Try Your Hand

  1. Create a WeakMap and store some metadata related to a user object.
  2. Use get() to retrieve the data.
  3. Check if the key exists using has().
  4. Delete the key from the WeakMap.