Search code examples
javascripttypescriptobjectreferenceinstance

What happens if an instance of an object has no references to it?


I wonder if an instance of an object that lacks of any reference will end up destroyed automatically / replaced with the time when new objects will be instanced.

For example:

let foo = new Object();
foo = "foo"

Does the instance created by new Object() gets destroyed, since there's no references to it anymore?

What happens to said instance in the memory?

Will said memory space get replaced the moment we do a new new Object()?


Solution

  • Does the instance created by new Object() gets destroyed, since theres no references to it anymore?

    Probably, eventually. The details are not something you can directly observe in code,¹ and are not covered by the JavaScript specification. Garbage collection (reclaiming memory that is no longer referenced by the app) is an incredibly complex area of JavaScript engines, and one that is constantly being reviewed and improved by the people who write and maintain those engines as they strive to make our code run as fast as they can.

    What happends to said instance in the memory?

    As far as your code is concerned, the instance is gone as soon as you no longer have a reference to it. In reality, the memory that instance used to occupy will probably be reclaimed (made available for future use) at some later time (possibly much later) when/if the garbage collector decides it needs to do that.

    Will said memory space get replaced the moment we do a new new Object()?

    It varies according to the JavaScript engine (V8 vs. SpiderMonkey vs. JavaScriptCore, etc.) and whether memory is abundant or in short supply. But again: As far as your code is concerned, the instance is gone the moment you can't reference it anymore.


    It's important not to write code based on observations or assumptions about the way garbage collection works for several reasons, including: It varies from JavaScript engine to JavaScript engine; it varies depending on the specific version of the engine; it varies depending on what else is going on.


    ¹ I should probably mention that JavaScript has just gotten a couple of new features (they'll be in the ES2021 spec): WeakRef and FinalizationRegistry which make it seem like you can observe garbage collection in your code. But those features have been carefully designed not to reveal too much about what the garbage collector is doing, so as to avoid having people write code based on what they see happening.