Created
October 19, 2017 11:45
-
-
Save stevieoj/b75ba7e12b227303348fd13e76697a08 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
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.