WeakMap Object (JavaScript)

A collection of key/value pairs in which each key is an object reference.


weakmapObj = new WeakMap()  


A WeakMap object cannot be enumerated.

If you add a value to the collection using an existing key, the new value will replace the old value.

In a WeakMap object, references to key objects are held 'weakly'. This means that WeakMap will not prevent a garbage collection from happening on the key objects. When there are no references (other than WeakMap) to the key objects, the garbage collector may collect the key objects.


The following table lists the properties of the WeakMap object.

Property Description
constructor Specifies the function that creates a WeakMap.
prototype Returns a reference to the prototype for a WeakMap.


The following table lists the methods of the WeakMap object.

Method Description
clear Removes all elements from a WeakMap.
delete Removes a specified element from a WeakMap.
get Returns a specified element from a WeakMap.
has Returns true if the WeakMap contains a specified element.
set Adds a new element to a WeakMap.
toString Returns a string representation of a WeakMap.
valueOf Returns the primitive value of the specified object.


The following example shows how to add members to a WeakMap object and then retrieve them.

var dog = {  
    breed: "yorkie"  

var cat = {  
    breed: "burmese"  

var wm = new WeakMap();  
wm.set(dog, "fido");  
wm.set(cat, "pepper");  

document.write(wm.get(dog) + ": ");  
document.write("<br />");  
document.write(wm.get(cat) + ": ");  

// Output:  
// fido: yorkie  
// pepper: burmese  


Supported in the Internet Explorer 11 standards document mode. Also supported in Store apps (Windows 8.1 and Windows Phone 8.1). See Version Information.
Not supported in the following document modes: Quirks, Internet Explorer 6 standards, Internet Explorer 7 standards, Internet Explorer 8 standards, Internet Explorer 9 standards, Internet Explorer 10 standards. Not supported in Windows 8.