JavaScript WeakMap And WeakSet Explained With Examples

JavaScript provides WeakMap and WeakSet to store collections of objects without preventing garbage collection. They are useful for memory-efficient data storage when working with objects.

This blog explains WeakMap and WeakSet with examples.


1. What Is WeakMap?

A WeakMap is a collection of key-value pairs where keys must be objects. WeakMaps do not prevent garbage collection of keys.

let wm = new WeakMap();
let obj = {name: "Sagar"};

wm.set(obj, "Developer");
console.log(wm.get(obj)); // Developer
console.log(wm.has(obj)); // true

wm.delete(obj);
console.log(wm.has(obj)); // false

Key Points:

  • Keys must be objects
  • Values can be any type
  • Cannot iterate over WeakMap
  • Automatically removes entries if key is garbage collected

2. What Is WeakSet?

A WeakSet is a collection of objects only. Each object is unique and can be garbage collected if there are no other references.

let ws = new WeakSet();
let obj1 = {name: "Sagar"};

ws.add(obj1);
console.log(ws.has(obj1)); // true

ws.delete(obj1);
console.log(ws.has(obj1)); // false

Key Points:

  • Only objects can be stored
  • Cannot iterate over WeakSet
  • Automatically removes objects if no other references exist

3. Why Use WeakMap & WeakSet

  • Efficient memory management
  • Prevent memory leaks for temporary object storage
  • Useful for private object properties in classes
  • Cannot be iterated, ensuring data privacy

Conclusion

WeakMap and WeakSet are advanced ES6 data structures ideal for storing objects without affecting garbage collection. They help developers manage memory efficiently while providing secure and private object storage.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *