LATEST 🚀 Welcome to Upgradix by Shrash Studio – Your destination for free technology learning and career growth.
🕘 Updated:
JavaScript

Set, Map, WeakSet and WeakMap in JavaScript

Set, Map, WeakSet and WeakMap in JavaScript. These are collections, which means they help us store and manage groups of values. Each one works differently. We use them to remove duplicate values, store key-value pairs, track objects and manage temporary data efficiently.

Set, Map, WeakSet and WeakMap in JavaScript: Complete Guide with Examples

Quick Answer: JavaScript provides four useful collection types. Set stores unique values, while Map stores key-value pairs. WeakSet stores weak references to objects, while WeakMap stores object-based key-value pairs. Choose the collection based on how you need to store and access data.

1. Why Do We Need These Collections?

Imagine you manage a pharmacy in Bengaluru. You receive prescriptions from hundreds of patients every day.

Each prescription has an ID. Each medicine has a stock quantity. Some patient records also need temporary metadata.

How would you store this information without repeating values?

The Problem: Using Only Arrays and Objects

We can start with arrays and ordinary objects. However, repeated values and lookups need extra work.

Example 1: Managing prescription IDs with an array

const prescriptionIds = [
  "RX101",
  "RX102",
  "RX101"
];

const medicineStock = {
  "Paracetamol": 120,
  "Cetirizine": 80
};

console.log(prescriptionIds);
console.log(medicineStock["Paracetamol"]);

Expected output

[ 'RX101', 'RX102', 'RX101' ]
120

This works, but it gets harder to manage as requirements grow.

What Goes Wrong?

  1. Duplicate prescription IDs remain in the array.
  2. We need extra logic to remove repeated values.
  3. Object keys are mainly strings and symbols.
  4. Object lookup does not directly provide collection methods.
  5. Temporary object metadata needs careful lifecycle management.

Now think about thousands of prescriptions and frequent updates.

The Solution: Choose the Right Collection

JavaScript provides four collections for different storage needs.

Set

Stores unique values.

Pharmacy use: Keep unique prescription IDs.

new Set()

Map

Stores key-value pairs.

Pharmacy use: Store medicine stock by medicine name.

new Map()

WeakSet

Stores weak references to objects.

Pharmacy use: Track active visit objects.

new WeakSet()

WeakMap

Stores values against weak object keys.

Pharmacy use: Attach private metadata to visit objects.

new WeakMap()

See How the Four Collections Differ

JavaScript Collections Set Unique values Any value type Map Key-value pairs Any key type WeakSet Unique object values Weak references WeakMap Object keys and values Weak key references Choose based on uniqueness, keys and object lifetime.

The animation highlights each collection and its main storage rule.

Without specialized collections versus using the right collection
Requirement Without collection With collection
Unique prescription IDs Array plus duplicate checks Set
Medicine stock by name Plain object Map
Track object membership Manual object flags or arrays WeakSet
Store metadata for an object Extra properties or separate storage WeakMap

The Ideas to Remember

  • Set = a collection that keeps unique values.
  • Map = a collection that connects keys with values.
  • WeakSet = a collection that weakly references objects.
  • WeakMap = a collection that stores values using weak object keys.
  • Garbage collection = JavaScript freeing memory that is no longer reachable.

2. Set in JavaScript

Set stores unique values. It keeps only one copy of each value.

It remembers the order in which values were inserted. It accepts values of any type.

How to Create and Use a Set

Let's store unique prescription IDs for our pharmacy.

Example 2: Create a Set of prescription IDs

const prescriptionIds = new Set();

prescriptionIds.add("RX101");
prescriptionIds.add("RX102");
prescriptionIds.add("RX101");

console.log(prescriptionIds.size);
console.log(prescriptionIds.has("RX102"));
console.log([...prescriptionIds]);

Expected output

2
true
[ 'RX101', 'RX102' ]

The duplicate RX101 is stored only once.

Important Set Methods

Common Set properties and methods
Method or property Purpose Example
add(value) Adds a value. ids.add("RX103")
has(value) Checks whether a value exists. ids.has("RX101")
delete(value) Removes one value. ids.delete("RX101")
clear() Removes every value. ids.clear()
size Returns the number of values. ids.size
forEach(callback) Runs a function for each value. ids.forEach(...)

Remove Duplicate Values from an Array

Set gives us a short way to remove repeated primitive values.

Example 3: Convert an array into unique prescription IDs

const receivedIds = [
  "RX101",
  "RX102",
  "RX101",
  "RX103",
  "RX102"
];

const uniqueIds = [...new Set(receivedIds)];

console.log(uniqueIds);

Expected output

[ 'RX101', 'RX102', 'RX103' ]

Important: Set compares objects by reference, not by their contents. Two separate objects with identical properties are still different values.

Example 4: Object values are compared by reference

const firstVisit = { patient: "Priya" };
const secondVisit = { patient: "Priya" };

const visits = new Set();
visits.add(firstVisit);
visits.add(secondVisit);

console.log(visits.size);

Expected output

2

3. Map in JavaScript

Map stores key-value pairs. Each key points to one value.

Unlike ordinary object keys, Map keys can have any value type.

Map also remembers the order in which entries were inserted.

How to Create and Use a Map

Let's store medicine names and their available stock.

Example 5: Store pharmacy stock using Map

const medicineStock = new Map();

medicineStock.set("Paracetamol", 120);
medicineStock.set("Cetirizine", 80);
medicineStock.set("Vitamin C", 65);

console.log(medicineStock.get("Paracetamol"));
console.log(medicineStock.has("Cetirizine"));
console.log(medicineStock.size);

Expected output

120
true
3

Important Map Methods

Common Map properties and methods
Method or property Purpose Example
set(key, value) Adds or updates an entry. stock.set("Vitamin C", 65)
get(key) Returns the value for a key. stock.get("Vitamin C")
has(key) Checks whether a key exists. stock.has("Vitamin C")
delete(key) Removes an entry. stock.delete("Vitamin C")
clear() Removes all entries. stock.clear()
size Returns the number of entries. stock.size
keys() Returns an iterator of keys. stock.keys()
values() Returns an iterator of values. stock.values()
entries() Returns key-value pairs. stock.entries()

Map Can Use Objects as Keys

This is one important difference from ordinary objects.

We can use a patient visit object as a Map key.

Example 6: Use an object as a Map key

const patientVisit = {
  patientName: "Priya",
  visitId: "VISIT501"
};

const visitPayments = new Map();

visitPayments.set(patientVisit, 450);

console.log(visitPayments.get(patientVisit));

Expected output

450

Map compares object keys by reference. The same object reference finds its entry.

Iterate Through a Map

We can use for...of to read every entry.

Example 7: Display medicine stock entries

const medicineStock = new Map([
  ["Paracetamol", 120],
  ["Cetirizine", 80],
  ["Vitamin C", 65]
]);

for (const [medicine, quantity] of medicineStock) {
  console.log(medicine + ": " + quantity);
}

Expected output

Paracetamol: 120
Cetirizine: 80
Vitamin C: 65

4. WeakSet in JavaScript

WeakSet stores objects without strongly keeping them alive.

Weak reference = a reference that does not stop garbage collection.

Garbage collection is the process that frees unused memory. JavaScript manages this process automatically.

WeakSet is useful when we need to track object membership. It does not keep objects alive by itself.

How to Create and Use a WeakSet

Let's track active patient visit objects in our pharmacy.

Example 8: Track active visit objects with WeakSet

const activeVisits = new WeakSet();

const priyaVisit = {
  visitId: "VISIT501",
  patientName: "Priya"
};

const raviVisit = {
  visitId: "VISIT502",
  patientName: "Ravi"
};

activeVisits.add(priyaVisit);
activeVisits.add(raviVisit);

console.log(activeVisits.has(priyaVisit));

activeVisits.delete(priyaVisit);

console.log(activeVisits.has(priyaVisit));

Expected output

true
false

Important WeakSet Methods

WeakSet methods
Method Purpose
add(object) Adds an object.
has(object) Checks whether the object exists.
delete(object) Removes the object.

Why Cannot We Iterate Through a WeakSet?

WeakSet does not expose its stored objects through iteration.

It has no size property, keys method or values method. This is intentional because garbage collection can change which objects remain available.

Example 9: WeakSet does not support normal iteration

const visits = new WeakSet();

const patientVisit = { visitId: "VISIT503" };

visits.add(patientVisit);

console.log(visits.has(patientVisit));
console.log(visits.size);
console.log(typeof visits[Symbol.iterator]);

Expected output

true
undefined
undefined

Remember: WeakSet accepts objects, not primitive values. You cannot add strings, numbers or booleans directly.

5. WeakMap in JavaScript

WeakMap stores key-value pairs using weak object keys.

Its keys must be objects or non-registered symbols in modern JavaScript environments. For broad compatibility, use objects as keys.

WeakMap is useful for storing metadata outside an object. The metadata does not keep its key object alive.

How to Create and Use a WeakMap

Let's store temporary information for each patient visit.

Example 10: Store visit metadata using WeakMap

const visitMetadata = new WeakMap();

const priyaVisit = {
  visitId: "VISIT501",
  patientName: "Priya"
};

visitMetadata.set(priyaVisit, {
  paymentStatus: "Paid",
  consultationRoom: "Room 4"
});

const metadata = visitMetadata.get(priyaVisit);

console.log(metadata.paymentStatus);
console.log(metadata.consultationRoom);
console.log(visitMetadata.has(priyaVisit));

Expected output

Paid
Room 4
true

Important WeakMap Methods

WeakMap methods
Method Purpose
set(key, value) Adds or updates an entry.
get(key) Returns the value for a key.
has(key) Checks whether a key exists.
delete(key) Removes an entry.

How WeakMap Helps with Object Lifetime

Consider a patient visit object stored in a WeakMap.

The application holds the visit object while the visit remains active. The WeakMap stores related metadata.

WeakMap object lifetime concept

Application reference
Patient visit object
WeakMap entry
Visit metadata
Reference removed
No other strong references
Eligible for collection
Entry can disappear with its key

The animation illustrates eligibility for garbage collection, not a fixed deletion time.

When no strong references remain, the key can become eligible for garbage collection.

The related WeakMap entry can then be removed by the engine. We cannot predict exactly when this happens.

Important: WeakMap does not guarantee immediate memory cleanup. Garbage collection timing is controlled by the JavaScript engine.

Why Cannot We Iterate Through a WeakMap?

WeakMap does not provide a list of its keys or entries. It also has no size property.

This avoids exposing a changing collection of objects. The engine can collect eligible keys at any time.

6. WeakSet vs WeakMap: What Is the Difference?

WeakSet and WeakMap comparison
Feature WeakSet WeakMap
Stores Objects Key-value pairs
Keys Not applicable Weak object keys
Values Objects themselves Any value
Duplicates No repeated object references One value per key
Iteration Not supported Not supported
Size property Not available Not available
Common use Track object membership Attach object metadata

7. Set vs Map vs WeakSet vs WeakMap

Complete JavaScript collection comparison
Feature Set Map WeakSet WeakMap
Stores Unique values Key-value pairs Objects Key-value pairs
Primitive values Yes Keys and values No Values only
Object keys Not applicable Yes Not applicable Yes
Iterable Yes Yes No No
Size property Yes Yes No No
Garbage collection aware No weak references No weak references Yes Yes
Insertion order Yes Yes Not exposed Not exposed
Best use Unique values Flexible lookup Object membership Object metadata

8. How Do We Choose the Right Collection?

Use the requirement to make your decision. Do not choose a weak collection only because it sounds faster.

Need unique values?Remove duplicates
Yes →
SetUnique values
Need key-value lookup?Find data by a key
Yes →
MapAny key type
Need to track objects?Only membership matters
Yes →
WeakSetWeak object references
Need object metadata?Keep data outside the object
Yes →
WeakMapWeak object keys

9. Common Mistakes and Best Practices

Mistake 1: Expecting Set to Compare Object Contents

Set checks object identity. It does not compare every property.

Wrong expectation

const visits = new Set();

visits.add({ visitId: "VISIT501" });
visits.add({ visitId: "VISIT501" });

console.log(visits.size);

Expected output

2

Better approach: Use a stable ID as the Set value.

Mistake 2: Using Map Like a Plain Object

Map does not use normal property access for stored entries.

Wrong approach

const stock = new Map();

stock.Paracetamol = 120;

console.log(stock.get("Paracetamol"));

Expected output

undefined

Correct approach: Use set() and get() for Map entries.

Corrected approach

const stock = new Map();

stock.set("Paracetamol", 120);

console.log(stock.get("Paracetamol"));

Expected output

120

Mistake 3: Trying to Iterate Through WeakMap

WeakMap is intentionally not iterable. Use Map when enumeration is needed.

Mistake 4: Storing Primitive Values in WeakSet

WeakSet is for objects. Use Set when you need primitive values.

Mistake 5: Expecting Immediate Garbage Collection

Removing a reference does not force immediate collection. Never write application logic that depends on its exact timing.

Best Practices

  • Use Set when you need unique values.
  • Use Map when keys can be objects or other values.
  • Use WeakSet to track object membership without keeping objects alive.
  • Use WeakMap for metadata linked to object lifetimes.
  • Use Map when you need iteration or collection size.
  • Do not use weak collections as caches that need manual enumeration.
  • Do not treat weak collections as a security or privacy boundary.

10. Performance and Real-World Considerations

Set and Map are designed for efficient membership checks and lookups.

The JavaScript specification requires average access performance to be sublinear. It does not promise one exact implementation or constant-time performance for every operation.

WeakSet and WeakMap solve a different problem. Their main benefit is weak object referencing.

For a pharmacy inventory, a normal Map is usually suitable. The application needs to list stock, update quantities and display entries.

For temporary metadata attached to an object, WeakMap may be a better fit. It avoids keeping the object alive only because metadata refers to it.

Production note: These collections exist in one JavaScript runtime. They do not automatically share data across browser tabs, Node.js processes or application servers.

11. How This Topic Comes Up in Interviews

Question 1: What Is the Difference Between Set and Map?

What the interviewer wants: They want to check your understanding of storage and lookup.

Strong answer: "Set stores unique values. Map stores key-value pairs. I use Set for unique prescription IDs. I use Map for medicine stock because each medicine has a quantity."

Question 2: Why Does WeakMap Not Support Iteration?

Strong answer: "WeakMap does not keep its object keys alive. The JavaScript engine can collect eligible keys. So, exposing a stable list of keys would be difficult. That is why WeakMap does not provide iteration or size."

Question 3: Can Map Use an Object as a Key?

Strong answer: "Yes. Map accepts objects as keys. It compares them by reference. I can use a patient visit object as a key and store its payment details."

Question 4: What Is the Difference Between WeakSet and WeakMap?

Strong answer: "WeakSet tracks whether an object exists in a collection. WeakMap stores a value against an object key. Both use weak references and neither supports normal iteration."

Question 5: Does WeakMap Immediately Remove an Entry?

Strong answer: "No. Removing the last strong reference makes an object eligible for garbage collection. The JavaScript engine decides when collection happens. We cannot depend on immediate cleanup."

What Senior Developers Should Also Explain

  • Map and Set use value equality rules based on SameValueZero.
  • Objects are compared by reference in Map and Set.
  • Weak collections are not substitutes for normal caches.
  • Memory management does not provide a predictable cleanup schedule.
  • Collection choice should follow access and lifecycle requirements.

12. Hands-On Practice

Beginner: Remove Duplicate Medicine Names

Create an array with repeated medicine names. Convert it into a Set.

Expected result: Each medicine name should appear once.

Intermediate: Build a Medicine Stock Map

Create a Map with five medicine names and their stock quantities.

  • Add one new medicine.
  • Update an existing quantity.
  • Check whether a medicine exists.
  • Print all medicine names and quantities.

Advanced: Track Patient Visit Objects

Create a WeakSet for active visit objects. Add two visits.

Check one visit, then remove it. Check its membership again.

Expert: Store Metadata in WeakMap

Create a WeakMap for patient visit metadata. Store payment status and room details.

Retrieve the metadata using the original visit object. Then remove the entry.

13. Quick Revision

  • Set: Unique values with iteration and a size property.
  • Map: Key-value pairs with flexible key types.
  • WeakSet: Weakly referenced objects without iteration.
  • WeakMap: Values stored against weak object keys.
  • Garbage collection: The engine manages unused memory.

14. Next Steps and Community

You now understand all four JavaScript collection types. Try each example in your browser console or Node.js environment.

Next, explore JavaScript iterators, generators and the iterable protocol. These topics help you understand how collections work with loops and spread syntax.

For deeper reference, explore the documentation:

Share your implementation, discuss alternatives and help other developers learn.

Learn Technology. Build Your Future.
Upgradix by Shrash Studio — Quality Technology Education. Completely Free.

Comments & Ratings (0)

Log in or create a student account to comment and rate this article.

Be the first to comment on this article.