Background: I found this question when I assumed that WeakMap
could store primitive data types, but was intrigued/confused as to how that would work. So this answer is something of a "proof by contradiction"…
The point of WeakMap
is that it only keeps an entry while its key is "alive". This is relatively easy to define for real objects: if there are any references to an object — n.b. usage as a key in a WeakMap
does not count as a reference! — then that object is "alive".
How would this work for primitive types? The number 1
doesn't really cease to exist if there are no "references" to it; but on the other hand even with code like
let a = 1;
let b = 1;
let c = a;
neither a
nor b
nor c
"reference" that number anyway! What makes a primitive type primitive is that any possible value of that type has no independent existence, they are all just potential values of a variable/property. Potential states of a variable like null
/true
/false
are similar to numbers like 1
or 42
, and even strings follow the same rules. [Let's ignore symbol type….] While a JavaScript engine might optimize internally, ES2015 as a language doesn't really have a mechanism for saying whether a state like "abc"
is "alive" or not.
If you were to store an entry of "abc" → "DEF"
in a WeakMap
, how long would you expect it to live? With objects, once an object goes "out of scope" there's no way to bring it back. But with primitives you end up with a situation where you can always re-create "abc"
in a call like:
let someWeakMap = new WeakMap();
(function () {
let key = "abc",
value = "DEF";
someWeakMap.set(key, value);
})();
setInterval(() => {
let revivedKey = "abc",
storedValue = someWeakMap.get(revivedKey);
console.log("Does it remember?");
console.log(storedValue === "DEF");
}, 1e3);
but who's to say how long the WeakMap
should remember the stored value?