WeakRef
Creates a new WeakRef object which holds a weak reference to the target object that does not prevent garbage collection
Syntax
new WeakRef(target)Parameters
| Parameter | Type | Description |
|---|---|---|
| target | object | The target object to hold a weak reference to |
Return Value
A new WeakRef instance
Examples
let obj: { data: string } | undefined = { data: 'Hello' }
const ref = new WeakRef(obj)
console.log(ref.deref()?.data) // 'Hello'class Cache<T extends object> {
private refs = new Map<string, WeakRef<T>>()
set(key: string, value: T) { this.refs.set(key, new WeakRef(value)) }
get(key: string): T | undefined { return this.refs.get(key)?.deref() }
}function createWeakCallback(target: object, callback: () => void) {
const ref = new WeakRef(target)
return () => {
if (ref.deref()) callback()
else console.log('Target was garbage collected')
}
}Understanding WeakRef
The WeakRef method in JavaScript creates a new WeakRef object which holds a weak reference to the target object that does not prevent garbage collection. It belongs to the WeakRef object and is one of the most widely used methods for working with weakref values in modern JavaScript and TypeScript applications.
The method signature is new WeakRef(target). It accepts 1 parameter: target. When called, it returns a new weakref instance. Understanding when and how to use WeakRef() helps you write more expressive, readable code.
Common use cases for WeakRef include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like weakref-deref, finalizationregistry-constructor, weakmap-set, enabling you to chain operations together for complex data manipulation pipelines.
Supported in Chrome 84+, Firefox 79+, Safari 14.1+, Edge 84+, Node.js 14.6+.
Browser Compatibility
Supported in Chrome 84+, Firefox 79+, Safari 14.1+, Edge 84+, Node.js 14.6+.
Related Methods
WeakRef.prototype.derefReturns the target object of the WeakRef if it has not been garbage collected, otherwise returns undefined
FinalizationRegistryCreates a new FinalizationRegistry that invokes a cleanup callback after a registered target object is garbage collected
WeakMap.prototype.setAdds or updates an element with a specified key and value to a WeakMap where the key must be an object or symbol
More WeakRef Methods
Other methods in the WeakRef object
Related Tools
More WeakRef Methods
Explore JavaScript Methods
Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.