What is WeakRef in JavaScript: Simple Explanation and Example
WeakRef in JavaScript is a special object that holds a weak reference to another object, allowing that object to be garbage collected if there are no other strong references. It helps manage memory by not preventing cleanup of objects that are only weakly referenced.How It Works
Imagine you have a box holding a toy. Normally, if you keep holding the box, the toy stays with you. But if you only have a note saying "the toy is somewhere," you don't actually keep the toy. WeakRef works like that note. It points to an object without forcing JavaScript to keep it in memory.
This means if no other part of your program is using the object strongly, JavaScript can clean it up to save memory. The weak reference won't stop this cleanup. Later, if you want to use the object, you can try to get it from the weak reference, but it might be gone.
Example
This example shows creating a weak reference to an object and how to access it safely.
let obj = { name: 'toy' }; const weakRef = new WeakRef(obj); console.log('Before cleanup:', weakRef.deref()); // Remove strong reference obj = null; // Suggest garbage collection (not guaranteed) // In real environments, GC runs automatically setTimeout(() => { const derefObj = weakRef.deref(); console.log('After cleanup:', derefObj); }, 1000);
When to Use
Use WeakRef when you want to keep a reference to an object but don't want to stop JavaScript from cleaning it up if it's no longer needed elsewhere. This is useful in caching, where you want to reuse objects if they exist but allow memory to be freed when under pressure.
For example, if you store large images or data objects temporarily, weak references let you avoid memory leaks by not forcing those objects to stay alive forever.
Key Points
- WeakRef holds a weak reference that does not prevent garbage collection.
- You must check if the object still exists using
deref()before using it. - It helps manage memory in caches or temporary storage.
- Garbage collection timing is unpredictable, so weak references may become
undefinedanytime.
Key Takeaways
WeakRef allows referencing objects without preventing their cleanup by garbage collection.deref() to safely access the object from a weak reference.