JavaScript WeakMap

JavaScript WeakMap is a data structure introduced in ES6 that allows you to store key-value pairs in a way that is much more efficient than traditional JavaScript objects. WeakMap objects are used to store weakly held objects, meaning that the keys and values can be garbage collected if they are no longer referenced anywhere else in your code.

Why should you use it?

  • WeakMap objects are more efficient than traditional JavaScript objects.
  • Keys and values can be garbage collected if they are no longer referenced.
  • WeakMap objects are not iterable, which can be useful for security.

WeakMap

WeakMaps are a type of collection that allow you to store key-value pairs where the keys are objects and the values can be anything. Unlike Maps, WeakMaps are not iterable, meaning you cannot loop through them. This makes them ideal for storing data that should not be exposed to the public, such as private data or data that should not be modified. Additionally, WeakMaps are garbage collected, meaning that any object that is no longer referenced will be automatically removed from the WeakMap. To create a WeakMap, you use the WeakMap constructor. The constructor takes an array of key-value pairs as an argument.
const myWeakMap = new WeakMap([
  [{name: 'John'}, 'John Doe'],
  [{name: 'Jane'}, 'Jane Doe'],
]);
The WeakMap constructor takes an array of key-value pairs, where the keys are objects and the values can be anything. The WeakMap constructor also takes an optional second argument, which is a function that will be called when an object is removed from the WeakMap. To add or update a value in a WeakMap, you use the set() method. The set() method takes two arguments, the first is the key and the second is the value.
myWeakMap.set({name: 'Bob'}, 'Bob Doe');
To retrieve a value from a WeakMap, you use the get() method. The get() method takes one argument, the key. The get() method will return the value associated with the key, or undefined if the key does not exist.
const name = myWeakMap.get({name: 'John'});
console.log(name); // 'John Doe'
To check if a key exists in a WeakMap, you use the has() method. The has() method takes one argument, the key. The has() method will return true if the key exists, and false if the key does not exist.
const hasKey = myWeakMap.has({name: 'John'});
console.log(hasKey); // true
To remove a key-value pair from a WeakMap, you use the delete() method. The delete() method takes one argument, the key. The delete() method will return true if the key-value pair was successfully deleted, and false if the key does not exist.
const result = myWeakMap.delete({name: 'John'});
console.log(result); // true
1