Bayu’s vault: a 1 MB archive, its strong holds, and the WeakRef ticket that does not keep it. A real WeakRef and FinalizationRegistry; when the browser sweeps…
Why it matters
A cache of something heavy (a big parsed file, a decoded image) may vanish when memory is needed: with a WeakRef that cache does not keep it all forever. A FinalizationRegistry helps tidy up related resources after the object is swept.
The key idea
A WeakRef holds without keeping, and the browser decides when to sweep
Common mistakes
Data you counted on suddenly turns into undefined Always check what it gives: const o = ref.deref(); if (!o) rebuild(). Once the last strong hold is gone, deref() may give undefined at any time. A WeakRef is only for data that may vanish.
The object does not vanish at once after cache = null= null only lets go of one hold. The browser sweeps later, when it likes, and a FinalizationRegistry callback comes later still, if it comes. Never depend on the timing.
The object is never swept though every reference you see is gone One strong hold anywhere (a history array, a cache Map, a closure, another object’s property, even a registry’s held value) is enough to keep it. A WeakRef does nothing while a strong hold remains.
Try it in this playground
Ask ref.deref() while the archive is held A strong hold guarantees it is there.
Let go of every strong hold Not gone yet: only allowed to be swept.
Register the archive with a FinalizationRegistryfr.register(arsip, 'arsip Pak Yusuf').
Make a WeakRef to a text Only objects can be held weakly.