Es6 Weakmap class examples in javascript | Typescript
- Admin
- Sep 20, 2023
- Es6 Javascript Typescript
WeakMap class in Javascript
Es6 introduced new collection data, and structure classes. WeakMap
is one of the collection class similar to Map class,Other Classes are Set, Map and WeakSet.Other Classes are Set, Map and WeakSet
WeakMap
is a map class that stores keys and values, and keys store weak references, which means that if the key’s reference is unreferenced, the value for the given key is garbage collected.
As a result, a weak map saves weak references to a key object. When the key object is referenced/destroyed, the garbage collector automatically removes the entry (key and value) from WeakMap, resulting in less memory consumption.
Typescript has no support for Map or WeakMap, Typescript is an extended version of javascript/ES6, which We can use with some configuration.
Es6 classes can be used in typescript with configuring the Es6 library in typescript configuration.
In the tsconfig.json file, add “lib”: [“es6”] or you can add polyfill.js for this classes.
Typescript has no built-in classes supported for Map, But Typescript supports the same data structure that ES6 supports.
How to declare and create WeakMap in javascript?
WeakMap Empty
is created using the new keyword.
new WeakMap();
Can also create using iterable objects, these objects contain key and values pairs
new WeakMap(iterable : Object)
For example, We will create a Map using an array of keys and values.
var key = { id: 1 };
var value = { name: "kiran" };
var map = new WeakMap([[key, value]]);
console.log(map);
Output is
[[Entries]]: Array(1)
0: {Object => Object}
key: {id: 1}
value: {name: "kiran"}
length: 1
weakmap Methods
WeakMap has only methods for adding/removing, checking keys, and empty map operations. iterable operations are not implemented.
WeakMap.set() method
It stores keys and values in the map Syntax.
set(key : Object, value : Object) : WeakMap
Primitive types - String, Boolean, Number, Undefined, and Symbole Objects are not allowed for the key value. Only objects are allowed.
var weakMap = new WeakMap();
var key = { id: 1 };
weakMap.set(key, "v");
console.log(weakMap.has(key));
console.log(weakMap.has(null));
Output is
[[Entries]]: Array(1)
0: {Object => "v"}
key: {id: 1}
value: "v"
length: 1
WeakMap.has() method
has() method returns true if the key already exists, else false
has(key : Object) : Boolean
the parameter is the object key Example Here is an example of has method usage.
var weakMap = new WeakMap();
var key = { id: 1 };
weakMap.set(key, "v");
console.log(weakMap.has(key)); //true
console.log(weakMap.has(null)); // false
WeakMap.delete() method
This method is used to remove the key from a map and true if exists, else false. Syntax:
delete(key : Object) : Boolean
Example here is an example of delete method usage
var weakMap = new WeakMap();
var key = { id: 1 };
weakMap.set(key, "v");
console.log(weakMap.delete(key)); // true
console.log(weakMap.delete(null)); // false
Allowed and not allowed Keys Example
keys of WeakMap not allowed primitive types and Symbole object and gives compilation error - Argument of type ‘Symbol’ is not assignable to a parameter of type ‘object’.
var map = new WeakMap();
map.set(new Date(), function currentTime() {}); // acceptable
map.set(() => "key", { objectkey: "objectvalue" }); // acceptable
map.set(1, 123); // not acceptable, primitive not allowed as keys
map.set(Symbol("symbol"), [6, 21]); // not acceptable, Symbole not allowed as keys
console.log(map);
WeakMap and Map Usage difference example
Following is an example of Map and WeakMap methods usage.
var map = new Map();
var weakMap = new WeakMap();
var object1 = { one: "two" };
var object2 = { five: "six" };
map.set(object1, "kiran");
weakMap.set(object2, "kiran2");
console.log(map.get(object1)); // kiran
console.log(map.get(object2)); // undefined
var map = new Map();
var weakMap = new WeakMap();
var object1 = { one: "two" };
var object2 = { five: "six" };
map.set(object1, "frank");
weakMap.set(object2, "frank2");
console.log(map.get(object1)); // frank
console.log(weakMap.get(object2)); // frank2
Difference between Map and WeakMap
Both used to store keys and values only
Set | WeakMap |
---|---|
Map Keys are strong references | Keys of WeakMap are weakly referenced |
Memory Consumption is high | Memory Consumption is less, the entry will be automatically garbage collected if any keys are unreferenced |
Keys can be a Primitive types like Strings, numbers, Date, Symbols, Functions, Objects, and Dates | Keys cannot be Primitive types and Symbol objects, Other objects are allowed |
Map has iterator implementation methods like keys(),values(), entries() and forEach() methods | Weakmap not not implemented iterator, so keys and values are not iterable |