How to Use Weak References in JavaScript: Syntax and Examples
In JavaScript, you can use
WeakRef to create a weak reference to an object, allowing it to be garbage collected if no strong references exist. Use new WeakRef(object) to create it and deref() to access the object safely.Syntax
The WeakRef constructor creates a weak reference to an object. You use new WeakRef(targetObject) to create it. To access the original object, call deref() on the weak reference, which returns the object if it still exists or undefined if it was garbage collected.
javascript
const weakRef = new WeakRef(targetObject); const obj = weakRef.deref(); if (obj) { // use obj safely } else { // object was garbage collected }
Example
This example shows creating a weak reference to an object and accessing it. If the object is still alive, it prints its property. If garbage collected, it prints a message.
javascript
let obj = { name: 'Alice' }; const weakRef = new WeakRef(obj); console.log('Before nulling obj:', weakRef.deref()?.name); // Alice // Remove strong reference obj = null; // Force garbage collection is not possible in JS, but after some time obj may be collected setTimeout(() => { const derefObj = weakRef.deref(); if (derefObj) { console.log('Object still alive:', derefObj.name); } else { console.log('Object has been garbage collected'); } }, 1000);
Output
Before nulling obj: Alice
Object still alive: Alice
Common Pitfalls
- Assuming the object always exists: The weak reference may return
undefinedif the object was garbage collected, so always check before use. - Using weak references for important data: WeakRefs are for caching or memory-sensitive cases, not for essential program data.
- Forgetting to keep a strong reference: If no strong references exist, the object can be collected anytime.
javascript
const weakRef = new WeakRef({ data: 123 }); // Wrong: assuming object is always there console.log(weakRef.deref().data); // May throw if object collected // Right: check before use const obj = weakRef.deref(); if (obj) { console.log(obj.data); } else { console.log('Object no longer exists'); }
Output
TypeError: Cannot read property 'data' of undefined
123
Quick Reference
Use this cheat sheet to remember how to work with WeakRef:
| Operation | Syntax | Description |
|---|---|---|
| Create weak reference | new WeakRef(object) | Creates a weak reference to the object |
| Access object | weakRef.deref() | Returns the object or undefined if collected |
| Check existence | if (weakRef.deref()) | Verify object is still alive before use |
Key Takeaways
Use
WeakRef to hold weak references that don't prevent garbage collection.Always check
deref() result before using the referenced object.Weak references are useful for caches or memory-sensitive data, not critical data.
Objects with no strong references can be collected anytime, so weak refs may become undefined.
Avoid accessing weak references without null checks to prevent runtime errors.