JavaScript – Weak Map


What is a Weak Map ?

Weak Map is a javascript object similar to Map.

Like Map, Weak Map stores the elements in key-value pair.

The only difference between Map and Weak Map is

1. In Map key-value pairs are the reference key and its value assigned to it.

2. In Weak Map the keys are the objects and its values are its arbitrary values.

Syntax :

new WeakMap([iterable])  

Iterable:

This defines an array and other iterable object whose elements are in the form of key-value pair.


Example :

<script>  
			var weakmap = new WeakMap();  
			var obj1 = {};  
			var obj2 = {};  
			var obj3= {};  
			weakmap.set(obj1, "Name");  
			weakmap.set(obj2, "Age");  
			weakmap.set(obj3, "Location");  
			console.log(weakmap);
		</script>

Output :

How Weak Map works in javascript ?

1. WeakMap object allows the keys of object type only.

2. And if there is no reference to a key object,then it will be moved to garbage collection.

3. The keys are not enumerable. So, it doesn’t provide any method to get the list of keys.


4. WeakMap object iterates its elements in insertion order.

Free online javascript course !!!

Click to Learn More about – Javascript online learning

Methods of WeakMap Object

WeakMap is used to store the collection of objects, and some of the methods are listed below.

SnoMethod / FunctionDescription
1delete()delete() method deletes the specified element from the WeakMap object.
2get()get() method returns the value of the specified key.
3has()has() method indicates whether the WeakMap object contains the specified value element.
4set()set() method adds or updates the key-value pairs to WeakMap object.