Open In App

What is WeakMap in ES6 ?

Improve
Improve
Like Article
Like
Save
Share
Report

WeakMap is a new Data Structure or Collection introduced in ES6. WeakMaps allows you to store a collection of Key-Value pairs. It adopts the same properties of Map. The Major difference is that keys of WeakMap cannot be a primitive data type. The keys must be of type object and values can be of any data type. 

Another major difference is that the key of WeakMap is weakly referenced. It means that whenever an object is used as a key for WeakMap, that object can be garbage collected. It can happen when the reference to that object is lost( i.e. assign that object reference to NULL). And when the object is no longer in use, JavaScript Garbage Collection detects it and frees it from the memory. Therefore keys of WeakMaps are weakly referenced.

Syntax:

const m = new WeakMap();

Parameters: It is an Iterable object whose Elements are in form of Key-Value Pair.

 

Functions of WeakMap:

  • set(key, value): It is used to add an element(Key-Value Pair) to the WeakMap Object.
  • get(key): It returns the Value associated with the specified “key”.
  • has(key): This function is used to check if the “key” specified exists in WeakMap or not. Returns true if it is present and false if it is not present.
  • delete(key): Remove an element of specified “key”, from the WeakMap Object.

Example: JavaScript Code to show the Working of these Functions.

Javascript




// Creating a WeakMap Object
const m = new WeakMap();
  
// Adding elements in it
  
// Remember, only object can
// be a key in WeakMap
obj1 = {} 
m.set(obj1, "Object 1");
obj2 = {}
m.set(obj2, "Object 2");
  
// Use delete() function
m.delete(obj2);
  
// Print the WeakMap
console.log(m);
  
// Using get() function to get 
// specific element in WeakMap
console.log(m.get(obj1));
  
// Using has() function to check
// if a particular element is 
// present in WeakMap or not.
console.log(m.has(obj1));


Output: Following is the output of the above code in the browser.

Explanation:

  • The First line is printing the contents of the WeakMap.
  • We deleted the obj2 before printing it, therefore it’s not displayed in the console.
  • In the Second line, we used the .get(obj1) function, and therefore it returned the Value i.e. Object 1.
  • The third line is we tried to find whether obj1 exist in WeakMap ‘m’ or not, and it returned true.

Last Updated : 05 Aug, 2021
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads