W3cubDocs

/JavaScript

WeakMap.weakMap

The WeakMap() creates WeakMap objects which are a collections of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.

You can learn more about WeakMaps in the section WeakMap object in Keyed collections.

Syntax

new WeakMap([iterable])

Parameters

iterable
Iterable is an Array or other iterable object whose elements are key-value pairs (2-element Arrays). Each key-value pair will be added to the new WeakMap. null is treated as undefined.

Examples

Using WeakMap

const wm1 = new WeakMap(),
      wm2 = new WeakMap(),
      wm3 = new WeakMap();
const o1 = {},
      o2 = function() {},
      o3 = window;

wm1.set(o1, 37);
wm1.set(o2, 'azerty');
wm2.set(o1, o2); // a value can be anything, including an object or a function
wm2.set(o3, undefined);
wm2.set(wm1, wm2); // keys and values can be any objects. Even WeakMaps!

wm1.get(o2); // "azerty"
wm2.get(o2); // undefined, because there is no key for o2 on wm2
wm2.get(o3); // undefined, because that is the set value

wm1.has(o2); // true
wm2.has(o2); // false
wm2.has(o3); // true (even if the value itself is 'undefined')

wm3.set(o1, 37);
wm3.get(o1); // 37

wm1.has(o1); // true
wm1.delete(o1);
wm1.has(o1); // false

Specifications

Browser compatibilityUpdate compatibility data on GitHub

Desktop
Chrome Edge Firefox Internet Explorer Opera Safari
WeakMap() constructor 36 12 6 11 23 8
new WeakMap(iterable) 38 12 36 No 25 9
WeakMap() without new throws 36 12 42 11 23 9
new WeakMap(null) 36 12 37 11 23 8
Mobile
Android webview Chrome for Android Firefox for Android Opera for Android Safari on iOS Samsung Internet
WeakMap() constructor 37 36 6 24 8 3.0
new WeakMap(iterable) 38 38 36 25 9 3.0
WeakMap() without new throws 37 36 42 24 9 3.0
new WeakMap(null) 37 36 37 24 8 3.0
Server
Node.js
WeakMap() constructor 0.12
0.12
0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.
new WeakMap(iterable) 0.12
WeakMap() without new throws 0.12
new WeakMap(null) 0.12
0.12
0.10
Disabled
Disabled From version 0.10: this feature is behind the --harmony runtime flag.

See also

© 2005–2018 Mozilla Developer Network and individual contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://wiki.developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap/WeakMap