Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

WeakMap

A Map whose keys must be objects and do not prevent garbage collection.

Available since: ES2015

Syntax

new WeakMap(entries)

Parameters

ParameterTypeDescription
entriesIterableOptional. [object, value] pairs to start with.

Return value

WeakMapA new collection with weak keys.

Examples

Extra data for an object without changing the object:

const clicks = new WeakMap();
const button = { id: 'save' };
 
clicks.set(button, 1);
clicks.set(button, clicks.get(button) + 1);
 
console.log(clicks.get(button));
console.log(clicks.has({ id: 'save' }));

Output:

2
false

Notes

When nothing else refers to a key object, its entry disappears by itself — this prevents memory leaks. The price: a WeakMap has no size, cannot be iterated, and strings and numbers cannot be keys.

See also

  • Map — A collection of key–value pairs where a key can be anything.
  • WeakSet — A set of objects that does not prevent their garbage collection.

In the tutorial

  • Map and Set — The Map and Set collections in JavaScript: a dictionary with keys of any type and a set of unique values.

Thanks for reading!

Donate to the site — we work hard for you.