A WeakMap in JavaScript is a special type of Map that stores key–value pairs, where keys must be objects and are held weakly.
This allows objects to be garbage collected automatically, making WeakMap useful for memory-efficient data handling.
What is WeakMap in JavaScript?
A WeakMap:
-
Stores key–value pairs
-
Allows only objects as keys
-
Holds keys weakly (no memory leaks)
-
Does not support iteration or size
WeakMap is commonly used for:
-
Caching object-related data
-
Storing private data
-
Tracking metadata
-
Memory-sensitive applications
Creating and Using WeakMap
Explanation:
-
set(key, value)→ adds an object key with a value -
get(key)→ retrieves value using the object key -
has(key)→ checks if key exists -
delete(key)→ removes the entry -
Keys must always be objects
Invalid Keys in WeakMap
Only object keys are allowed:
WeakMap vs Map (Key Differences)
-
WeakMap keys must be objects
-
WeakMap does not support looping
-
WeakMap has no
sizeproperty -
Entries are removed automatically when keys are garbage collected
Why WeakMap Is Important
Understanding WeakMap in JavaScript helps you:
-
Avoid memory leaks
-
Manage object-specific data safely
-
Build efficient applications
-
Handle private data patterns
-
Improve performance in large systems
Quick Summary
-
WeakMap stores object keys only
-
Supports
set(),get(),has(),delete() -
No iteration or size
-
Automatic garbage collection
-
Ideal for memory-sensitive logic
Conclusion
WeakMap in JavaScript is designed for advanced object-based data storage.
It provides a safe and memory-efficient way to associate data with objects, making it a valuable tool in modern JavaScript applications.