MENU
WeakRef
A WeakRef object, added in ECMAScript 2021, holds a weak reference to a target object — one that does not, by itself, keep that object alive in memory. Call .deref() to obtain the target object, or undefined if it has already been garbage-collected.
Caching is a typical use case: the cache should not be the reason a large object stays in memory once nothing else needs it.
let cache = new Map();
function getData(key, load) {
let ref = cache.get(key);
let value = ref && ref.deref();
if (value !== undefined) return value;
value = load();
cache.set(key, new WeakRef(value));
return value;
}Because garbage collection timing is not observable or guaranteed, WeakRef should be reached for only as a last resort, eg. for caches and mapping tables, and never to implement functionality that is otherwise observable from a script (the target's disappearance is inherently non-deterministic, and some engines may never collect it at all within a short-lived program).