WeakMap in JavaScript – The Secret Keeper You Didn’t Know You Needed!
JavaScript
WeakMap
Data Structure

WeakMap in JavaScript – The Secret Keeper You Didn’t Know You Needed!

Explore what WeakMap is in JavaScript, how it's different from Map, when to use it, real-world examples, and common pitfalls—explained in a beginner-friendly, no-fluff way.
atapasatapas3 min read

What is a WeakMap?

A WeakMap is like a regular Map, but with one juicy twist:

Its keys must be objects, and it holds them weakly — meaning it won’t stop them from being garbage collected.

Think of WeakMap as:

A magic box that only an object can open and take out the things from it. When the object leaves, the magic box also disappears.

When Should You Use WeakMap?

Use WeakMap when you want to:

  • Associate truly private data with an object.
  • Avoid memory leaks with temporary objects.
  • Hide implementation details from external code.

It is especially helpful:

  • When you don’t want to expose internal states or metadata directly.
  • When you want data to vanish when the object is no longer used.

A Real World Example

Imagine you’re building a UI where you want to track the last time each DOM element was clicked. You want to accomplish it without storing the data directly on the element or risking memory leaks when elements are removed from the DOM. This is where WeakMap shines.

Why Use WeakMap Here?

  • You want to store data related to a DOM node.
  • You don’t want to manually delete it when the node is removed.
  • WeakMap allows automatic cleanup when the node is gone from memory.

Let us assume a HTML code snippet with two DIVs:

HTML
<div id="box1">Click Me!</div>
<div id="box2">Click Me Too!</div>

Let us now create a WeakMap clickTimestamps to store the click metadata:

JS
const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");

// Create a WeakMap to store click metadata
const clickTimestamps = new WeakMap();

function handleClick(event) {
  const element = event.target;
  const now = new Date();

  clickTimestamps.set(element, now);

  console.log(`Element clicked at: ${clickTimestamps.get(element).toLocaleTimeString()}`);
}

box1.addEventListener("click", handleClick);
box2.addEventListener("click", handleClick);

What Happens Behind the Scenes?

  • The WeakMap stores the timestamp associated with each DOM element.
  • You don’t pollute the DOM element with extra properties.
  • When the element (say box2) is removed from the DOM and garbage collected, its associated timestamp in WeakMap is automatically cleaned up. No leaks!

How’s It Different from a Map?

As we know about the WeakMap, here is a comparison table of WeakMap vs. Map:

map vs weekmap

WeakMap is non-enumerable and non-inspectable — perfect for hiding things.

Pitfalls to Watch Out For

A few pitfalls you need to be aware of when using a WeakMap:

  • You can’t loop through a WeakMap.
  • You can’t check its size.
  • You can’t see what’s inside it (on purpose!).
  • If the object key disappears, so does the value—it’s gone forever.

Just like WeakMap, we also have WeakSet serves a similar purpose. However, it is a collection of unique elements, not a map. I wish to cover it in a future tidbit.

That's all for now. Found this helpful? Please snap a like, and feel free comment below.

Want to learn further?

Check out the session on JavaScript Collections: Map, Set, WeakMap, and WeakSet.

Day 33: JavaScript Map, Set, WeakMap, WeakSet - When & Why to Use Them! 🤩 - In this session, we take a deep dive into JavaScript Collections—Map, Set, WeakMap, and WeakSet. Whether you’re a beginner or brushing up on advanced JavaScript, this session will help you understand when to use each, their key differences, and real-world use cases with clear examples.

Learn Full Stack

with tapaScript

By clicking Sign Up you re confirming that you agree with our Terms and Conditions.

newsletter

Don't forget to connect with us on