JavaScript’s FinalizationRegistry 🌟

Nikhil Gupta
2 min readMay 26, 2024

--

Introduction

Today, we delve into a powerful yet often overlooked feature: the FinalizationRegistry. This allows us to schedule cleanup tasks for objects that are about to be garbage collected.

Sounds intriguing, right ❓ Let’s dive in 🏊‍♂️

🖥️ What is FinalizationRegistry?

It is a JavaScript feature that lets you register callbacks to be invoked when an object becomes eligible for garbage collection.

💭 Think of it as setting up a reminder to clean up after yourself when you’re done playing with your toys. 🧹

📝 How Does It Work?

To use FinalizationRegistry, you first create an instance and provide a callback function. This function will be called when the registered objects are garbage collected.

const registry = new FinalizationRegistry(heldValue => {
console.log(`Cleanup for ${heldValue} triggered.`);
});

Next, you register objects with the registry. Each object comes with a “held value,” which is passed to the callback when the object is garbage collected.

const myObject = {
name: "My Object"
};
registry.register(myObject, "Held Value");

🕒 Timing Is Key

  • It’s important to remember that the timing of cleanup callbacks is not guaranteed.
  • They might execute immediately after the object is garbage collected, or they might wait until the current JavaScript event loop completes. 🕰️

🚫 Caution Ahead

While FinalizationRegistry is a powerful tool, it’s not meant for critical operations. Its unpredictability makes it unsuitable for essential program logic. 🚨

🛠️ Practical Example

Imagine you’re building a web app that generates temporary data structures. Instead of manually clearing them, you can use FinalizationRegistry to automate the cleanup process.

const tempDataRegistry = new FinalizationRegistry(heldValue => {
console.log(`Cleaning up temporary data: ${heldValue}`);
});

function generateTempData() {
const tempData = {
id: Date.now(),
data: "Temporary Data"
};
tempDataRegistry.register(tempData, "Generated Temp Data");
}
generateTempData(); // Generates temporary data and registers it for cleanup

🌈 Conclusion

  • FinalizationRegistry is a fascinating tool for managing memory in JavaScript.
  • It automates the cleanup of objects that are about to be garbage collected, helping to optimize performance and resource usage.
  • However, its use should be approached with caution, especially considering the timing and reliability of cleanup callbacks. 🌈

If you enjoyed this article, please make sure to Like & Subscribe 🌐

For more updates Follow me on LinkedIn

--

--

Nikhil Gupta

👨‍💻 Software Engineer | Passionate about Crafting Seamless User Experiences 🚀