What's the difference between ES6 Map and WeakMap?

Dmitrii Sorin picture Dmitrii Sorin · Mar 24, 2013 · Viewed 27.9k times · Source

Looking this and this MDN pages it seems like the only difference between Maps and WeakMaps is a missing "size" property for WeakMaps. But is this true? What's the difference between them?

Answer

kshirish picture kshirish · May 28, 2015

They both behave differently when a object referenced by their keys/values gets deleted. Lets take the below example code:

var map = new Map();
var weakmap = new WeakMap();

(function(){
    var a = {x: 12};
    var b = {y: 12};

    map.set(a, 1);
    weakmap.set(b, 2);
})()

The above IIFE is executed there is no way we can reference {x: 12} and {y: 12} anymore. Garbage collector goes ahead and deletes the key b pointer from “WeakMap” and also removes {y: 12} from memory. But in case of “Map”, the garbage collector doesn’t remove a pointer from “Map” and also doesn’t remove {x: 12} from memory.

Summary: WeakMap allows garbage collector to do its task but not Map.

References: http://qnimate.com/difference-between-map-and-weakmap-in-javascript/