Es6 Weakmap class examples in javascript | Typescript

WeakMap class in Javascript

ES6 introduced new collection data structures and classes. WeakMap is one of these collection classes, similar to the Map class. Other classes are Set, Map and WeakSet

WeakMap is a map class that stores keys and values, with keys storing weak references. This means that if the key’s reference is unreferenced, the value for the given key is garbage collected.

As a result, a WeakMap saves weak references to a key object. When the key object is referenced or destroyed, the garbage collector automatically removes the entry (key and value) from the WeakMap, resulting in less memory consumption.

TypeScript does not have built-in 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 by configuring the ES6 library in the TypeScript configuration. In the tsconfig.json file, add “lib”: [“es6”], or you can add a polyfill for these classes.

How to Declare and Create a WeakMap in JavaScript?

An empty WeakMap is created using the new keyword:

new WeakMap();

You can also create one using iterable objects, which contain key and value pairs:

new WeakMap(iterable : Object)

For example, let’s create a WeakMap using an array of keys and values:

var key = { id: 1 };
var value = { name: "kiran" };
var map = new WeakMap([[key, value]]);
console.log(map);

The 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 emptying the map. Iterable operations are not implemented.

  • WeakMap.set() Method This method stores keys and values in the map. The syntax is:

    set(key: Object, value: Object): WeakMap

    Primitive types such as String, Boolean, Number, Undefined, and Symbol 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

    The has() method returns true if the key already exists, otherwise false.

    has(key : Object) : Boolean

    The parameter is the object key.

    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. It returns true if the key exists, otherwise false.

    Syntax:

    delete(key : Object) : Boolean

    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

WeakMap Allowed and not allowed Keys Example

Keys of WeakMap do not allow primitive types and Symbol objects, and compilation errors occur Argument of type 'Symbol' is not assignable to a parameter of type 'object'. For example:

var map = new WeakMap();
map.set(new Date(), function currentTime() {}); // acceptable
map.set(() => "key", { objectkey: "objectvalue" }); // acceptable
map.set(1, 123); // not acceptable, primitive types not allowed as keys
map.set(Symbol("symbol"), [6, 21]); // not acceptable, Symbol not allowed as keys
console.log(map);

WeakMap and Map Usage Difference Example

Below 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 are used to store keys and values. Below is a comparison:

SetWeakMap
Map Keys are strong referencesKeys of WeakMap are weakly referenced
Memory Consumption is highMemory Consumption is less, the entry will be automatically garbage collected if any keys are unreferenced
Keys can be Primitive types like Strings, numbers, Date, Symbols, Functions, Objects, and DatesKeys cannot be Primitive types and Symbol objects, Other objects are allowed
Map has iterator implementation methods like keys(), values(), entries(), and forEach() methodsWeakMap does not implement iterators, so keys and values are not iterable