No announcement yet.

What is a WeakMap

  • Filter
  • Time
  • Show
Clear All
new posts

  • What is a WeakMap

    What is a WeakMap

    The WeakMap object is a collection of key/value pairs in which the keys are weakly referenced. In this case, keys must be objects and the values can be arbitrary values. The syntax is looking like as below,

    new WeakMap([iterable])
     var ws = new WeakMap();
    var user = {};
    ws.has(user); // true
    ws.delete(user); // removes user from the map
    ws.has(user); // false, user has been removed

  • #2
    The main difference is that references to key objects in Map are strong while references to key objects in WeakMap are weak. i.e, A key object in WeakMap can be garbage collected if there is no other reference to it. Other differences are,
    1. Maps can store any key type Whereas WeakMaps can store only collections of key objects
    2. WeakMap does not have size property unlike Map
    3. WeakMap does not have methods such as clear, keys, values, entries, forEach.
    4. WeakMap is not iterable.


    • #3
      Below are the list of methods available on WeakMap,
      1. set(key, value): Sets the value for the key in the WeakMap object. Returns the WeakMap object.
      2. delete(key): Removes any value associated to the key.
      3. has(key): Returns a Boolean asserting whether a value has been associated to the key in the WeakMap object or not.
      4. get(key): Returns the value associated to the key, or undefined if there is none. Let's see the functionality of all the above methods in an example,
      var weakMapObject = new WeakMap();
      var firstObject = {};
      var secondObject = {};
      // set(key, value)
      weakMapObject.set(firstObject, 'John');
      weakMapObject.set(secondObject, 100);
      console.log(weakMapObject.has(firstObject)); //true
      console.log(weakMapObject.get(firstObject)); // John


      Related Topics