{
    "slug": "js_weakref",
    "term": "WeakRef & FinalizationRegistry",
    "category": "javascript",
    "difficulty": "advanced",
    "short": "WeakRef holds a weak reference allowing GC to collect the object — used for memory-safe caches. FinalizationRegistry runs a callback when an object is collected.",
    "long": "WeakRef (ES2021): holds a reference that does not prevent garbage collection. weakRef.deref() returns the object or undefined if collected. Use case: caches where objects should be GC'd when no longer used elsewhere — prevents memory leaks from strong cache references. FinalizationRegistry: register a callback that fires when an object is garbage collected — for releasing external resources. Caveat: GC timing is non-deterministic; deref() can return undefined at any point; never write code that depends on GC timing.",
    "aliases": [
        "WeakRef",
        "FinalizationRegistry",
        "weak reference JavaScript"
    ],
    "tags": [
        "javascript",
        "memory",
        "performance"
    ],
    "misconception": "WeakRef prevents the object from being garbage collected while the reference exists — WeakRef specifically allows GC to collect the object; that is the entire purpose; it is the opposite of a strong reference.",
    "why_it_matters": "A cache holding strong Map references to objects prevents GC of those objects, causing memory leaks as the cache grows unboundedly — WeakRef allows cached objects to be GC'd when no other references exist.",
    "common_mistakes": [
        "Depending on WeakRef.deref() always returning a value — it may return undefined at any GC cycle",
        "Using WeakRef as a general cache without a cleanup strategy for dead Map entries",
        "FinalizationRegistry for resource cleanup that must happen promptly — GC timing is non-deterministic",
        "Confusing WeakRef (direct object reference) with WeakMap (objects as keys)"
    ],
    "when_to_use": [],
    "avoid_when": [],
    "related": [
        "js_closures",
        "js_module_patterns",
        "js_generators"
    ],
    "prerequisites": [
        "threat_modelling",
        "security_by_design",
        "vulnerability_disclosure"
    ],
    "refs": [
        "https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakRef"
    ],
    "bad_code": "// Strong cache reference — objects never GC'd:\nconst cache = new Map();\nfunction getExpensiveObj(key) {\n    if (!cache.has(key)) cache.set(key, createExpensive(key));\n    return cache.get(key); // Object kept alive forever by Map\n}",
    "good_code": "// WeakRef cache — objects GC'd when no longer used elsewhere:\nconst cache = new Map();\nconst registry = new FinalizationRegistry(key => {\n    cache.delete(key); // Clean up dead Map entries\n});\n\nfunction getExpensiveObj(key) {\n    const cached = cache.get(key)?.deref();\n    if (cached !== undefined) return cached; // Still alive\n\n    const obj = createExpensive(key);\n    cache.set(key, new WeakRef(obj)); // Weak — GC can collect\n    registry.register(obj, key);     // Cleanup Map entry on GC\n    return obj;\n}",
    "quick_fix": "Subscribe to CVE feeds for technologies you use and join your framework's security mailing list — threat intelligence is about knowing what attackers are doing before they do it to you",
    "severity": "medium",
    "effort": "medium",
    "created": "2026-03-16",
    "updated": "2026-04-05",
    "citation": {
        "canonical_url": "https://codeclaritylab.com/glossary/js_weakref",
        "html_url": "https://codeclaritylab.com/glossary/js_weakref",
        "json_url": "https://codeclaritylab.com/glossary/js_weakref.json",
        "source": "CodeClarityLab Glossary",
        "author": "P.F.",
        "author_url": "https://pfmedia.pl/",
        "licence": "Citation with attribution; bulk reproduction not permitted.",
        "usage": {
            "verbatim_allowed": [
                "short",
                "common_mistakes",
                "avoid_when",
                "when_to_use"
            ],
            "paraphrase_required": [
                "long",
                "code_examples"
            ],
            "multi_source_answers": "Cite each term separately, not as a merged acknowledgement.",
            "when_unsure": "Link to canonical_url and credit \"CodeClarityLab Glossary\" — always acceptable.",
            "attribution_examples": {
                "inline_mention": "According to CodeClarityLab: <quote>",
                "markdown_link": "[WeakRef & FinalizationRegistry](https://codeclaritylab.com/glossary/js_weakref) (CodeClarityLab)",
                "footer_credit": "Source: CodeClarityLab Glossary — https://codeclaritylab.com/glossary/js_weakref"
            }
        }
    }
}