2

Suppose i have an Array of objects in javascript :

var obj0 = new Object();
var obj1 = new Object();
var obj2 = new Object();
var obj3= new Object();

var array = new Array(obj0,obj1,obj2,obj3);

if i write :

array[1] = null;

this will give me [obj0,null,obj2,obj3] what was nulled is the array case not the object itself; the obj1 won't really be nulled in the memory.

How to null an object by accessing it via the array ?

Bardelman
  • 2,176
  • 7
  • 43
  • 70
  • 3
    You should really be using literal syntax, eg: `var array = [{}, {}, {}, {}];` – Kpower Jan 02 '14 at 18:14
  • Kpower, i think you said THE RIGHT solution !! if i don't create any variable then the object isn't referenced and once the array cell is nulled then the object will disappear once the GC runs. but for me, i didn't created objects i'm trying to null so it won't work for me. – Bardelman Jan 02 '14 at 18:34

5 Answers5

5

You just need to remove all references to the object, including the obj1 reference. Then the garbage collector will take care of the rest.

However, if your obj1 variable is a local variable (as it appears to be in your code snippet), you can just leave the reference as is. When the enclosing method returns, the local variable will be cleaned up, and subsequently, the nulled object as well.

Gopherkhan
  • 4,317
  • 4
  • 32
  • 54
1

I found a good article on Smashing Magazine that looks relevant to your question.

It’s not possible to force garbage collection in JavaScript. You wouldn’t want to do this, because the garbage collection process is controlled by the runtime, and it generally knows best when things should be cleaned up.

http://coding.smashingmagazine.com/2012/11/05/writing-fast-memory-efficient-javascript/

photodow
  • 255
  • 2
  • 8
0

i think "splice()" will help:

http://www.w3schools.com/jsref/jsref_splice.asp

var obj0 = new Object();
var obj1 = new Object();
var obj2 = new Object();
var obj3= new Object();

var array = new Array(obj0,obj1,obj2,obj3);
array.splice(1); // kill index 1

The result: [obj0,obj2,obj3].

JSX
  • 28
  • 1
  • 3
0

What if you tried to write it this way?

var array = new Array();

array[0] = new Object();
array[1] = new Object();
array[2] = new Object();
array[3]= new Object();

array[1] = null;
photodow
  • 255
  • 2
  • 8
0

As commented Kpower, writting :

var array = [{}, {}, {}, {}];

or

   var array = new Array(new Object(),
                         new Object(),
                         new Object(),
                         new Object());

and when nulling any array cell like :

array[1] = null;

this will effectively remove the reference for the object so it will be garbage collected.

Bardelman
  • 2,176
  • 7
  • 43
  • 70