Skip to main content
Practice Problems

What are WeakMap, WeakSet, and WeakRef?

markdown
# Understanding WeakMap, WeakSet, and WeakRef ## Introduction In JavaScript, `WeakMap`, `WeakSet`, and `WeakRef` are specialized data structures that allow for the management of memory more efficiently. This document provides an overview of each, including their characteristics, use cases, and examples. ## Set Consent Preferences ### Necessary Cookies ### Performance Cookies - **_ga_*:** ### Advertising Cookies ### Uncategorized Cookies Other uncategorized cookies are those that are being analyzed and have not yet been classified into a category. No cookies to display. ### User Actions - **[Reject]** - **[Save my preferences]** - **[Accept all]** --- ## WeakMap ### Overview `WeakMap` is a `key → value` map, similar to a regular `Map`, but with an important difference: 1. Keys can only be objects. 2. These keys are stored as weak references. ### Weak References Explained **What is a “weak reference” and why is it needed?** In a regular `Map`, it’s easy to create a situation where an object is no longer needed, but it still “lives” in memory because there is a reference to it as a key. The GC (`Garbage Collector`) might think: “there is still a reference to this object - so it cannot be collected.” In **WeakMap**, this is not the case: if there are no strong references to the key object anywhere else, the GC can collect the object, and the entry in `WeakMap` will also be removed automatically. This means there is less chance of a memory leak. This structure cannot be iterated, so there are no: `for...of`, `.keys()`, `.entries()`, and even `.size`. The API is minimal: `set / get / has / delete`. ### Typical Use Case To store “private” data/metadata for objects (cache, state, calculations) without creating a memory leak. ```javascript const sessionData = new WeakMap(); let clientInfo = {username: "Alice"}; sessionData.set(clientInfo, {activeSince: Date.now()}); console.log(sessionData.get(clientInfo)); // { activeSince: ... } clientInfo = null; // now the object can be collected by GC, and the entry in WeakMap will also be removed automatically.

WeakSet

Overview

WeakSet is like a Set (unique values), but it only contains objects, and they are also stored as weak references. Just like the previous structure, Set cannot be iterated.

Typical Use Case

To mark objects (for example, “already processed”) without preventing the GC from collecting them.

javascript
const uniqueReferences = new WeakSet(); let objectRef = {endpoint: "/api/products"}; uniqueReferences.add(objectRef); console.log(uniqueReferences.has(objectRef)); // true objectRef = null; // the object can be garbage collected, and WeakSet won't "retain" it

WeakRef

Overview

WeakRef is a wrapper that holds a weak reference to an object (also called target or referent). The logic here is: you are kind of “holding a handle” on the object, but you do not guarantee that it will exist forever. At any moment, the GC can collect it.

Typical Use Case

Very cautious caching/optimizations when you want to “peek” at an object but not hold it in memory forcibly. It is important that WeakRef cannot be relied upon as stable data storage — deref() may return undefined at any moment.

javascript
let profileInfo = {name: "alice_smith"}; const softProfileRef = new WeakRef(profileInfo); console.log(softProfileRef.deref()); // { name: "alice_smith" } profileInfo = null; // later... const retrievedProfile = softProfileRef.deref(); console.log(retrievedProfile); // either the object or undefined (if GC has collected it)

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems