Skip to content

Instantly share code, notes, and snippets.

@stevieoj
Created October 19, 2017 11:45
Show Gist options
  • Save stevieoj/b75ba7e12b227303348fd13e76697a08 to your computer and use it in GitHub Desktop.
Save stevieoj/b75ba7e12b227303348fd13e76697a08 to your computer and use it in GitHub Desktop.
var k1 = {a: 1};
var k2 = {b: 2};
var map = new Map();
var wm = new WeakMap();
map.set(k1, 'k1');
wm.set(k2, 'k2');
k1 = null;
map.forEach(function (val, key) {
console.log(key, val); // k1 {a: 1}
});
k2 = null;
wm.get(k2); // undefined
@stevieoj
Copy link
Author

As you see, after removing k1 key from the memory we can still access it inside the map. At the same time removing k2 key of WeakMap removes it from wm as well by reference.

That's why WeakMap hasn't enumerable methods like forEach, because there is no such thing as list of WeakMap keys, they are just references to another objects.

@stevieoj
Copy link
Author

And keys of WeakMaps are of the type Object only. Primitive data types as keys are not allowed (e.g. a Symbol can't be a WeakMap key).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment