When are JavaScript objects destroyed?

In C++ I can define a constructor and destructor explicitly, and then cout << "C or D Called" from with in the constructor/destructor function, to know exactly where.

However in JavaScript how do I know when an object is destructed. The example below is the case that concerns me.

I'm calling an internal function on a timeout and I'm wondering if the object stays alive as long as the timer is running, waiting to call next again.

User Click calls Control

// Calls  Control

Control calls Message

var message_object = new Message( response_element );

Message calls Effects

new Effects().fade( this.element, 'down', 4000 );
message_object.display( 'empty' );


 *Effects - build out as needed
 *  element - holds the element to fade
 *  direction - determines which way to fade the element
 *  max_time - length of the fade

var Effects = function(  ) 
    this.fade = function( element, direction, max_time ) 
        element.elapsed = 0;
        clearTimeout( element.timeout_id );
        function next() 
            element.elapsed += 10;
            if ( direction === 'up' )
                element.style.opacity = element.elapsed / max_time;
            else if ( direction === 'down' )
                element.style.opacity = ( max_time - element.elapsed ) / max_time;
            if ( element.elapsed <= max_time ) 
                element.timeout_id = setTimeout( next, 10 );



JS objects don't have destructors per se.

JavaScript objects (and primitives) are garbage collected when they become inaccessible, meaning when there is no possible reference to them in the current execution context. The JavaScript runtime has to continuously monitor for this. So unless you use the delete keyword to remove something, then its destruction is sort of under the hood. Some browsers are bad at detecting references left in closure scope (I'm looking at you, Redmond) and that's why you often see objects being set to null at the end of functions--to make sure that memory is freed in IE.


This notion that object destruction is reducible to garbage collection for memory strikes me as dangerously misleading, as the problem isn't reducible to freeing memory.

Destructors are responsible for releasing other resources, such as file descriptors or event listeners, which aren't dealt with automagically by garbage collection. In such cases destructors are absolutely required to unwind state before memory is released, or you will leak resources.

In such cases it's a problem that destructors aren't a first-class notion, whether they need to be called explicitly or can be called implicitly after an object becomes unreachable.

The best way to deal with this is to document your modules appropriately if they need destructors to be used and to underline resource leak scenarios failing such use.


There is no dynamic memory managment in ECMAscript at all. A Garbage Collector will take care of anything that required memory in your script. So actually the question should be more like,

"How does the Garbage Collector know when it can free memory for objects"

Simply spoken, most GC's look if there are any active references. That might be due to parent context object, prototype chains or any direct access to a given object. In your particular instance, anytime setTimeout gets executed, it'll call next() which closes over the .fade() parent context and the .face() function in turn holds a closure to the Effects function( context ).

That means, as long as there are calls to setTimeout, that whole construct is held in memory.

You can help old'ish GC implementations sometimes a little bit, by nulling variables-/references to it is able to collect some stuff earlier or at all, but modern implementatios are pretty smart about this stuff. You actually don't have to care about things like "Object/Reference live times".


There is an experimental Firefox and Chrome function window.requestIdleCallback() that calls back when the browser is idle. This could be used to simulate a class instance destructor.

Almost the same effect can be obtained from the following code:

    // Simulate destructor here

This sets an automatically-dismissed timeout that completes when the current JavaScript script completes (and the main event loop resumes).


Another important consideration is circular references in data structures: "A refers to B, and B refers to A, and no one anymore refers to either of them." Theoretically this could cause both A and B to be seen as uncollectible, hence a memory-leak.

The topic has been discussed here, with some fairly recent updates:

Is it possible to create a "weak reference" in javascript?

The strategy therein discussed is to "weaken" one of the references between A and B so that the garbage-collector knows it can be broken, thus leading to them eventually being reaped ... or maybe stolen in an out-of-memory situation.

Of course it's also possible to benefit from discipline. If you know you're not going to use something anymore, write a routine that sets its various reference-fields to Null before you abandon it to the garbage collector ... "Be tidy."

Garbage collection strategies in JavaScript have advanced considerably since their earliest implementations since the language has become so important. When you are studying texts on this topic, be sure that they are recent.


I'm familiar with about 8 different common programming languages. Coming from a C++ environment you will find that virtually no language except C++ gets destructors right. The first deficiency (from a C++ viewpoint) is that destruction is considered to only be about memory. Executing a user defined function such as closing a file handle or terminating a network connection as part of destruction is not possible. A few languages do let you write custom destructors but they have the second failing which is, they don't execute the destructor at the instant the object goes out of scope. They take their time about it, whenever it's convenient for the runtime. This makes them unusable in some contexts such as releasing multithread locks or automatically closing dialog boxes, or perhaps getting the current microsecond timestamp to measure function execution time, no matter how the function was exited. But, you just have to realize this and accept those limitations and hopefully the other nice features of the language compensate.


Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.