WeakRef

WeakRef

Creates a new WeakRef object which holds a weak reference to the target object that does not prevent garbage collection

Syntax

JavaScript
new WeakRef(target)

Parameters

ParameterTypeDescription
targetobjectThe target object to hold a weak reference to

Return Value

A new WeakRef instance

Examples

Basic Usage
let obj: { data: string } | undefined = { data: 'Hello' }
const ref = new WeakRef(obj)
console.log(ref.deref()?.data) // 'Hello'
Practical Example
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() }
}
Advanced Usage
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

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.