DEV Community

Debug Diaries
Debug Diaries

Posted on

JavaScript Explained: Set, WeakSet, Map & WeakMap – What They Are and When to Use Them

JavaScript isn’t just about arrays and objects anymore. As applications grow complex, we need smarter ways to store and manage data. That's where Set, WeakSet, Map, and WeakMap come in.

These built-in data structures provide more powerful and flexible options for working with collections. Let’s dive deep into each one, understand how they work, and when to use them in real-world scenarios.

Set – A Collection of Unique Values

What is it?
A Set is a special type of collection in JavaScript that lets you store unique values — no duplicates allowed.
You can think of a Set like a checklist where each item can appear only once.

Key Features:

  • Stores unique values only.
  • Values can be of any data type – numbers, strings, objects, etc.
  • Maintains the insertion order.
  • Provides utility methods like .add(), .has(), .delete(), and .clear().
const fruits = new Set(); fruits.add('apple'); fruits.add('banana'); fruits.add('apple'); // Duplicate, won’t be added again console.log(fruits); // Set(2) { 'apple', 'banana' } console.log(fruits.has('banana')); // true 
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • You need a list of unique items (e.g., tags, filters).
  • You want to easily check for the presence of a value.
  • You want to remove duplicates from an array:

Example:

const arr = [1, 2, 2, 3]; const uniqueArr = [...new Set(arr)]; console.log(uniqueArr); // [1, 2, 3] 
Enter fullscreen mode Exit fullscreen mode

WeakSet – Sets with Weak References

What is it?

A WeakSet is similar to a Set, but it only stores objects and holds them "weakly," meaning:

  • The object references don’t prevent garbage collection.
  • If no other references to the object exist, it will be automatically removed from the WeakSet.

Key Features:

  • Only objects (not primitives) can be stored.
  • Items are held weakly and may be garbage collected.
  • Not iterable – you can't loop through a WeakSet.
  • Useful for memory-efficient temporary storage.

Example:

const person = { name: 'Alice' }; const visitedUsers = new WeakSet(); visitedUsers.add(person); console.log(visitedUsers.has(person)); // true // Later... // person = null; // If this happens, the object may be removed from WeakSet 
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • Tracking objects without creating memory leaks, like keeping track of DOM elements or users currently logged in.
  • You don’t need to iterate the collection.
  • You want automatic cleanup when the object is no longer used elsewhere.

Map – Key-Value Pairs with Powerful Features

What is it?
A Map is a collection of key-value pairs where keys can be any data type – unlike regular objects which only allow strings or symbols.

It’s like an enhanced Object but with predictable ordering and better performance for frequent additions/removals.

Key Features:

  • Any value (object or primitive) can be used as a key.
  • Maintains insertion order of key-value pairs.
  • Provides easy methods: .set(), .get(), .has(), .delete(), .clear(), and .size.

Example:

const userMap = new Map(); const user1 = { id: 1 }; userMap.set('name', 'John'); userMap.set(user1, 'Premium Member'); console.log(userMap.get('name')); // John console.log(userMap.get(user1)); // Premium Member 
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • You need keys that are not just strings.
  • You require frequent key-value pair manipulation.
  • You need guaranteed order of entries.
  • Ideal for building dictionaries, caching data, or implementing LRU caches.

WeakMap – Object Keys with Weak References

What is it?
A WeakMap is just like a Map, but with some constraints:

  • Only objects can be used as keys.
  • Those keys are held weakly, allowing them to be garbage collected.
  • It is not iterable and has limited methods.

Key Features:

  • Only object keys (no strings, numbers).
  • Automatically cleans up when the key object is no longer referenced.
  • Supports only .set(), .get(), .has(), and .delete().

Example:

const secretData = new WeakMap(); let user = { name: 'Tom' }; secretData.set(user, { accessLevel: 'admin' }); console.log(secretData.get(user)); // { accessLevel: 'admin' } user = null; // Now, the user object and its secret data can be garbage collected 
Enter fullscreen mode Exit fullscreen mode

When to Use:

  • Storing private data related to DOM elements or users.
  • You want memory-efficient key-value storage.
  • You don’t need to enumerate keys.

Final Thoughts

While JavaScript's built-in objects like arrays and plain objects are great, Set, WeakSet, Map, and WeakMap give you more power and flexibility when managing data — especially as your applications grow in complexity.

Remember:

  • Use Set and Map when you need iterable collections with full control.
  • Use WeakSet and WeakMap for memory-sensitive or private data management.

Mastering these will help you write cleaner, more efficient, and scalable JavaScript code.

Top comments (1)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.