View Full Version : Remove a variable

10-03-2008, 07:41 PM
If I use:

function test(){...}

testInstance = new test();

This variable named testInstance will become a global scope variable.

Can I removed it later if I do not need it?

(I mean if I have:

testInstance1 = new test();
testInstance2 = new test();

testInstance10 = new test();

For whatever purpose I need in my app, a lot of variable like testInstanceX will be created at the global level. So it may take some memory. I wonder If I can remove them once I do not need them, so to free the memory.)



(For a local variable such as

function test(){

var localVar;


Once it is out of the function scope, I believe the localVar will be automatically removed from the memory so I do not need to worry about it.


10-03-2008, 08:01 PM
testInstanceX = false; ??

10-03-2008, 09:01 PM
1: You don't really have to worry about it.
2: Javascript has a garbage collector, which means it will kill off certain values (not variables) it can prove will not be used again.

You probably want to use an array was well. For example:

function Test() {
this.blah = "blah";

var testInstance = [];
for(var i = 0; i < 100; ++i)
testInstance[i] = new Test();


testInstance[3] = null; // garbage collects what its value.
// NOTE: testInstance[3] still exists and still can be used.