- Регистрация
- 9 Май 2015
- Сообщения
- 1,483
- Баллы
- 155
What is a WeakMap?
A WeakMap is like a regular Map, but with one juicy twist:
Use WeakMap when you want to:
It is especially helpful:
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?
Let us assume an HTML code snippet with two DIVs:
<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:
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?
As we know about the WeakMap, here is a comparison table of WeakMap vs. Map:
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:
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 to comment below.
Want to learn further?
Check out the session on JavaScript Collections: Map, Set, WeakMap, and WeakSet.
A WeakMap is like a regular Map, but with one juicy twist:
Think of WeakMap as:Its keys must be objects, and it holds them weakly — meaning it won’t stop them from being garbage collected.
When Should You Use WeakMap?A magic box that only an object can open and take things from it. When the object leaves, the magic box also disappears.
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.
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 an HTML code snippet with two DIVs:
<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:
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!
As we know about the WeakMap, here is a comparison table of WeakMap vs. Map:
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 to comment below.
Want to learn further?
Check out the session on JavaScript Collections: Map, Set, WeakMap, and WeakSet.
- 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.
Источник: