What is the use of .clear() method in Javascript weakMap?

JavascriptObject Oriented ProgrammingProgramming

WeakMap is a collection in JavaScript. This type of collection is used to store the data in the form of key-value pairs. In WeakMap, the key must be definitely an object and the values can be of any type.

This collection is called as WeakMap because of the key which is mandated to be the object. An object can be garbage collected which is a disadvantage when compared with Map.

In JavaScript WeakMap, clear() function is used to delete the whole weakMap or removes all the elements in the weakMap.

Syntax

the syntax for weak map is as follows.

mapName.clear()

This will not take any parameters and clears all the elements in the given WeakMap.

Example 1

This example demonstrates the usage of clear() function in WeakMap in JavaSCriptL −

var wkMap=new Map(); wkMap.set(1,"Articles"); wkMap.set(2,"Reference APIs"); wkMap.set(3,"New Technologies"); console.log("WeakMap elements and size before invoking clear():","",wkMap, wkMap.size); wkMap.clear(); console.log("WeakMap elements and size after invoking clear():",wkMap,wkMap.size);

Example 2

This example demonstrates the usage of clear() function of WeakMap in JavaScript. In this example we are using the .has() following is the syntax of it.

WeakMapName.has(specificElement) // returns a Boolean result

If the current WeakMap object has the specified element this function returns true.

var wkMap=new Map(); wkMap.set(1,"Articles"); wkMap.set(2,"Reference APIs"); wkMap.set(3,"New Technologies"); console.log("WeakMap elements and size before invoking clear():",wkMap, wkMap.size); console.log("A specific element is present before using clear():",wkMap.has(1)) wkMap.clear(); console.log("WeakMap elements and size after invoking clear():",wkMap,wkMap.size); console.log("A specific element is present after using clear():",wkMap.has(1))

In the above example, the functionality of the clear() has been shown with using a different function of weakMap i.e., has() function. This function will return a Boolean result if the specified element is present or not in the WeakMap.

If a specified element is checked for its presence, before invoking the clear() function ,has() function returns ‘true’. If the same element is checked after the invocation of clear() function, then the has() will return ‘false’ which concludes that the element has been removed.

Example 3

Following is an implementation of you own WeakMap.

class ClearableWeakMap { constructor(init) { this._wm = new WeakMap(init) } clear() { this._wm = new WeakMap() } delete(key) { return this._wm.delete(key) } get(key) { return this._wm.get(key) } has(key) { return this._wm.has(key) } set(key, value) { this._wm.set(key, value) return this } } let weakMap = new ClearableWeakMap(); let obj = function() {}; weakMap.set(obj, "test"); console.log(weakMap.has(obj));
raja
Updated on 26-Aug-2022 11:58:18

Advertisements