When an object is created and a reference to it is stored in a
variable, the object's reference count is one. When the
reference to the object is copied and stored in another variable, the
reference count is incremented to two. When one of the two variables
that holds these references is overwritten with some new value, the
object's reference count is decremented back to one. If the
reference count reaches zero, there are no more references to the
object. Since there are no references to copy, there can never again
be a reference to the object in the program. Therefore, JavaScript
knows that it is safe to destroy the object and garbage collect the
memory associated with it.
Unfortunately, there are shortcomings to using reference counting as
a garbage-collection scheme. In fact, some people don't even
consider reference counting to be true garbage collection and reserve
that term for better algorithms, such as mark-and-sweep garbage
collection. Reference counting is a simple form of garbage collection
that is easy to implement and works fine in many situations. There is
an important situation, however, in which reference counting cannot
correctly detect and collect all garbage, and you need to be aware of
it.