WeakMap in ES6

Last Updated : 11 Jun, 2026

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. 

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.
Comment