FinalizationRegistry

FinalizationRegistry

Creates a new FinalizationRegistry that invokes a cleanup callback after a registered target object is garbage collected

Syntax

JavaScript
new FinalizationRegistry(callback)

Parameters

ParameterTypeDescription
callback(heldValue: any) => voidA callback invoked with the held value when the registered object is collected

Return Value

A new FinalizationRegistry instance

Examples

Basic Usage
const registry = new FinalizationRegistry((key: string) => {
  console.log(`Object with key '${key}' was garbage collected`)
})
const obj = { data: 'temp' }
registry.register(obj, 'my-key')
Practical Example
const registry = new FinalizationRegistry((id: number) => {
  console.log(`Cleaning up resource #${id}`)
  releaseResource(id)
})
function trackResource(id: number, resource: object) {
  registry.register(resource, id)
}
Advanced Usage
class LeakDetector {
  private registry: FinalizationRegistry<string>
  constructor() {
    this.registry = new FinalizationRegistry((label) => {
      console.warn(`[LeakDetector] '${label}' was collected`)
    })
  }
  track(obj: object, label: string) {
    this.registry.register(obj, label)
  }
}

Understanding FinalizationRegistry

The FinalizationRegistry method in JavaScript creates a new FinalizationRegistry that invokes a cleanup callback after a registered target object is garbage collected. It belongs to the FinalizationRegistry object and is one of the most widely used methods for working with finalizationregistry values in modern JavaScript and TypeScript applications.

The method signature is new FinalizationRegistry(callback). It accepts 1 parameter: callback. When called, it returns a new finalizationregistry instance. Understanding when and how to use FinalizationRegistry() helps you write more expressive, readable code.

Common use cases for FinalizationRegistry include data transformation, input validation, API response processing, and building reusable utility functions. It works well alongside related methods like finalizationregistry-register, finalizationregistry-unregister, weakref-constructor, 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 FinalizationRegistry Methods

Other methods in the FinalizationRegistry object

Related Tools

More FinalizationRegistry Methods

Explore JavaScript Methods

Browse our complete reference of 410 JavaScript methods with syntax, examples, and explanations.