WeakMaps in Javascript
The WeakMap
object is a collection of key/value pairs in which the keys are weakly referenced. The keys must be objects and the values can be arbitrary values.
Let’s talk about we have a class person and a property name.
Here is the example,
class Person {
constructor(name) {
this.name = name;
}
}
let Person1 = new Person("John");console.log(Person1); // Person { name: 'John' }
console.log(Person1.name); // John
We need to have a private variable in Javascript so that that name does not have access from the outside.
How we can do it ?
One solution would be to put underscores, for example,
class Person {
constructor(name) {
this._name = name;
}
}let Person1 = new Person("John");console.log(Person1); // Person { name: 'John' }
console.log(Person1.name); // Undefined
This brings with it the eternal struggle to warn everyone that underscoring cannot be changed or touched.
Another solution would be to use the data type Symbol(),
let s_name = Symbol();class Person {
constructor(name) {
this[s_name] = name;
}
}let Person1 = new Person("John");console.log(Person1); // Person { name: 'John' }
console.log(Person1.name); // Undefined
The problem is than Symbols are exposed with methods like Object.getOwnPropertySymbols(),
let symbols = Object.getOwnPropertySymbols(Person1);console.log(Person1[symbols[0]]); // John
But the most simple option is,
new WeakMap( [iterable] );
This object have one argument (iterable)
iterable -> Optional. 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.
So let´s create our WeakMap,
class Person {
constructor(name) {
let weakmap = new WeakMap();
weakmap.set(this, { name: name });
}
}let Person1 = new Person("John");console.log(Person1); // Person {}
console.log(Person1.name); // Undefined
The main differences to the Map object are
- WeakMap are collections of objects only.
- If an element object has no other reference left, it will be auto released to the garbage collector.
- For the previous reason you can´t iterate over objects inside of WeakMap.
- For the previous reason you can´t know the size of the objects inside of WeakMap.
- You can only use .set(), get(), .has() and .delete() methods with WeakMap.
WeakMaps can be particularly useful constructs when mapping keys to information about the key that is valuable only if the key has not been garbage collected.