Question:

Describe the WeakMap data structure and use code samples to explore its interface (unique qualities, initialization, adding items, accessing items, removing items, looking up the size, iteration, etc).


WeakMap - What’s that?

A weakmap is related to the map object. A map holds key and value pairs but the difference between a regular map and a weakmap is the latter can be garbage collected. This is a huge plus as we can prevent memory leaks like when we’re acessing a library of objects but don’t want to keep reference to the object after having used it.

Think of a map as a treasure map and there are several x’s to mark where our treasure is at. The x’s represent the key value pairs and are written in ink. So they can’t be erased. But in a weakmap the x’s are written in pencil so once we find the treasure we can erase it. This is what we call by being weakly being held.

The differences between WeakMap and Map

Weak map does not access to all the properties that map does this includes:

  • forEach
  • entries
  • keys
  • values
  • size

The properties that are available are :

  • delete
  • get
  • has
  • set

Weakmaps arent’ iterable thats why the listed properties aren’t available as then the weakmap would have to hold on to these values in memory.

How to make and add

To create a weapmap we use the following syntax:

let weakMap1 = new WeakMap(); 

To fill the weakmap we can do it this way :

let objKey1 = {},
    objKey2 = {},
    objKey3 = {};
 
let testWeakMap = new WeakMap([
    [objKey1, 'Weak value 1'],
    [objKey2, 'Weak value 2'],
    [objKey3, 'Weak value 3']
]);
console.log(testWeakMap.get(objKey2)); 

or we can use set to do it this way :

let obj1 = {},
    obj2 = document.querySelector('body'),
    obj3 = function () {return 'hello'}; 


let testMap = new WeakMap();

testMap.set(obj1,'object').set(obj2,'element').set(obj3,'function');

An important note about keys in weakmaps is that they must be objects which means they can be functions or dom references also. In regular maps we could use strings so this does make weakmaps quite limiting in this area.

Deleting

To delete a object in a weakmap we use delete:

 testMap.delete(obj1); 
 textMap.has(obj1); // false

If we want to delete all of our objects at once we use clear

 testMap.clear(); // now there all gone

## Size and Iteration

The size property does not work with weakmaps so there is no way to tell how many object there are. We also can’t use iteration so no forEach or those other properties. That’s just another draw back we have to deal with when it comes to weakmaps but can be worth it to prevent your web app from slowing to a crawl.