Skip to content

Object Lifecycle

Every object in a program goes through a lifecycle: from the moment it’s created (memory allocated) to the moment it’s destroyed (memory reclaimed). Understanding this lifecycle is crucial for writing efficient, leak-free code.


stateDiagram-v2
[*] --> Declaration: Variable declared
Declaration --> Allocation: new keyword
Allocation --> Initialization: Constructor called
Initialization --> Usage: Object ready
Usage --> Unreachable: No more references
Unreachable --> GC: Garbage collector runs
GC --> [*]: Memory reclaimed

StageWhat Happens
DeclarationReference variable created (null/undefined)
AllocationMemory allocated on heap
InitializationConstructor runs
UsageMethods called, properties accessed
UnreachableNo more references to the object
GCMemory reclaimed (non-deterministic timing)

class Resource {
constructor(name) {
this.name = name;
this.id = ++Resource.instanceCount;
}
use() { /* using the object */ }
dispose() { /* cleanup logic */ }
}
// Lifecycle
let res = new Resource("DB Connection"); // Created + Initialized
res.use(); // Used
res.dispose(); // Manual cleanup
res = null; // Eligible for GC

  • Clean up resources explicitly — close files, connections, sockets
  • Don’t rely on finalizers/destructors — they’re not deterministic
  • Nullify references to help GC (in long-lived collections)

Previous Topic: Abstract Classes → Next Topic: Memory Management →