• Что бы вступить в ряды "Принятый кодер" Вам нужно:
    Написать 10 полезных сообщений или тем и Получить 10 симпатий.
    Для того кто не хочет терять время,может пожертвовать средства для поддержки сервеса, и вступить в ряды VIP на месяц, дополнительная информация в лс.

  • Пользаватели которые будут спамить, уходят в бан без предупреждения. Спам сообщения определяется администрацией и модератором.

  • Гость, Что бы Вы хотели увидеть на нашем Форуме? Изложить свои идеи и пожелания по улучшению форума Вы можете поделиться с нами здесь. ----> Перейдите сюда
  • Все пользователи не прошедшие проверку электронной почты будут заблокированы. Все вопросы с разблокировкой обращайтесь по адресу электронной почте : info@guardianelinks.com . Не пришло сообщение о проверке или о сбросе также сообщите нам.

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

Sascha Оффлайн

Sascha

Заместитель Администратора
Команда форума
Администратор
Регистрация
9 Май 2015
Сообщения
1,483
Баллы
155
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 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 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!
How’s It Different from a Map?


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.


Источник:

Пожалуйста Авторизируйтесь или Зарегистрируйтесь для просмотра скрытого текста.

 
Вверх Снизу