What is the use of a WeakMap object in JavaScript ?
Last Updated :
28 Apr, 2025
What is a WeakMap?
A WeakMap is a collection of key/value pairs where the keys are objects and values are any JavaScript object.
It is similar to Map with some differences:
- It is not enumerable and the keys are private in nature.
- Allows garbage collection of any values if keys are not referenced from somewhere other than a WeakMap.
- Only objects are allowed as keys.
- It depends on garbage collection, introducing non-determinism.
Note: Keys cannot be Primitive data type (E.g. a string cannot be a WeakMap key).
Syntax:
new WeakMap([iterable])
Instance methods: It has 4 instance methods.
- WeakMap.prototype.delete( key ): It removes any value with the given key.
- WeakMap.prototype.get( key ): It returns the value with the given key, else undefined.
- WeakMap.prototype.has( key ): It returns a boolean value whether a value is a WeakMap object or not.
- WeakMap.prototype.set( key, value ): It sets the value of the given key in the WeakMap object.
Uses of WeakMap:
- It can be used in tracking object calls.
- It can be used in tracking libraries.
- It can be used as private property in a class.
- Keeping data about host objects like DOM nodes in the browser.
Note: Execute the below examples with node.js
Steps:
- Install node.js
- Execute node <filename.js> in CLI
Example 1: This is a basic use case of a WeakMap where we are referencing an empty object as a WeakMap key which gets garbage collected when assigned to "null" and automatically the WeakMap also gets set to "undefined" from "value".
JavaScript
const wm = new WeakMap();
let obj = {};
wm.set(obj, "value");
console.log(wm.get(obj));
obj = null;
console.log(wm.get(obj));
Output :
value
undefined
Example 2: In this example, you will understand to track objects with weakmap. You can count the number of times the object is passed to the function foo().
JavaScript
const objTracker = (() => {
const wm = new WeakMap();
return (obj) => {
wm.set(obj, (wm.get(obj) || 0) + 1);
return wm.get(obj);
}
})();
function foo(args) {
const count = objTracker(args);
console.log(`${JSON.stringify(args)} is called ${count} times`)
}
const obj1 = { key: 1 }
const obj2 = { key: 2 }
foo(obj1);
foo(obj1);
foo(obj2);
Output:
{"key":1} is called 1 times
{"key":1} is called 2 times
{"key":2} is called 1 times
Example 3: In this example, we create private props in class. This is similar to using private property with # as a prefix.
JavaScript
const Foo = (() => {
const wm = new WeakMap();
return class Fooclass {
constructor() {
wm.set(this, {
classname: 'Fooclass'
});
}
get name() {
return wm.get(this).classname;
}
}
})();
const obj1 = new Foo()
console.log(obj1.name)
Output:
Fooclass
Example 4: In this example, you will understand to do a special task with respect to the library methods, so that when they are called you can do something special around it. You can do something till the mod() function exists.
JavaScript
function mod(a, b) {
return a % b;
}
const lib = new WeakMap();
lib.set(mod, {
do: () => {
console.log('Something done');
}
})
lib.get(mod).do();
Output:
Something done
Similar Reads
What is the use of a WeakSet object in JavaScript ? Introduction: The JavaScript WeakSet object is a sort of collection that allows us to store items that are only loosely held. WeakSet, unlike Set, is just a collection of items. It does not include arbitrary values. It has the same features as a set, in that it does not hold duplicates. The main dis
3 min read
WeakSet vs WeakMap in JavaScript In JavaScript, there are two types of references strong and weak. The WeakSet and WeakMap are called weak references. Since these are weak references they do not prevent garbage collection if they are the only reference to the object in the memory. These objects are rarely used but are useful when w
2 min read
What is the difference between Map and WeakMap in JavaScript ? In this article, we will talk about the difference between Map and WeakMap which are introduced by ES6. Javascript object supports only one key object. For supporting multiple key objects, Then Map comes on this path. Map: A Map is an unordered list of key-value pairs where the key and the value can
4 min read
How to understand WeakMap in JavaScript ? The WeakMap object stores key/value pairs. The keys should be objects, and also the value may be anything. In JavaScript, a map API may be engineered with 2 arrays, one for keys and one for values that are shared by the four API functions. Setting parts on this map would entail at the same time inse
3 min read
JavaScript weakMap set() Method The weakMap.set() is an inbuilt function in JavaScript which is used to set a new element with a particular key and value to a WeakMap object. Syntax: weakMap.set(key, value); Parameters: It takes parameters "key" which is the key of the element which is to set to the WeakMap object and parameter "v
2 min read