JavaScript WeakMap()
The WeakMap() constructor creates WeakMap objects.
A WeakMap stores key-value pairs.
Unlike Map objects, WeakMap keys must be objects.
WeakMap keys are held weakly and can be removed automatically when no longer used elsewhere.
Syntax
new WeakMap()
new WeakMap(iterable)
Parameters
| Parameter | Description |
|---|---|
| iterable | Optional. An iterable object containing key-value pairs. |
Return Value
| Call | Returns |
|---|---|
new WeakMap() |
A WeakMap object |
new WeakMap(iterable) |
A WeakMap object initialized with entries |
Creating a WeakMap
Example
const wm = new WeakMap();
Object Keys Only
WeakMap keys must be objects.
Valid
const person = {};
const wm = new WeakMap();
wm.set(person, "John");
Invalid
const wm = new WeakMap();
wm.set("name", "John"); // Error
WeakMap vs Map
| WeakMap | Map |
|---|---|
| Keys must be objects | Keys can be any value |
| Not iterable | Iterable |
| No size property | Has a size property |
| Entries may be removed automatically | Entries remain until removed |
Common Methods
set()get()has()delete()
Note
For WeakMaps there is no:
- size
- keys()
- values()
- entries()
- forEach()
Not Iterable
WeakMap objects are not iterable.
WeakMap objects do not provide keys(), values(), or entries() methods.
Typical Use
WeakMap objects are often used to associate data with objects without preventing those objects from being removed from memory.
Example
const privateData = new WeakMap();
const person = {};
privateData.set(person, "secret");
Object Hierarchy
WeakMap objects inherit from Object.
Object └─ WeakMap
| What | Value |
|---|---|
| Constructor Type | Function |
| Creates | WeakMap objects |
| Inherits From | Object |
| Iterable | No |
| Object Keys Required | Yes |
WeakMap keys must be objects.
WeakMap objects are not iterable and do not have a size property.
Map/Set/WeakMap/WeakSet
| Object | Key-Value | Keys | Iterable |
|---|---|---|---|
| Object | Yes | String/Symbol | No |
| Map | Yes | Any Value | Yes |
| WeakMap | Yes | Objects Only | No |
| Set | Values Only | N/A | Yes |
| WeakSet | Values Only | Objects Only | No |
Browser Support
WeakMap() is an ECMAScript6 (ES6 2015) feature.
JavaScript 2015 is supported in all browsers since June 2017:
| Chrome 51 |
Edge 15 |
Firefox 54 |
Safari 10 |
Opera 38 |
| May 2016 | Apr 2017 | Jun 2017 | Sep 2016 | Jun 2016 |