0

Consider this multi-level nested JavaScript object.

function foo() {
    var channels = {
        2: {
            name: "station 1", 
            description: "station1",
            img: ["img1-a", "img1-b", "img1-c"]
        },
        3: {
            name: "station 2", 
            description: "station2",
            img: ["img2-a", "img2-b", "img2-c"]
        },
        4: {
            name: "station 3", 
            description: "station3",
            img: ["img3-a", "img3-b", "img3-c"]
        },
    };

    console.log(channels);          
};          
....                
// calling foo.
foo();

After the function foo() returns, will all the nested objects (i.e. the individual channel objects, strings, the array img, and the strings in img array, all be automatically garbage collected ?

Or, do I need to explicitly iterate through and "delete" each object?

p.campbell
  • 98,673
  • 67
  • 256
  • 322
Karthik
  • 1,006
  • 3
  • 10
  • 19

4 Answers4

2

They're eligible for GC as long as nothing else is referencing them.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
2

Depends on what happens in console.log. Certainly in Chrome, a reference to the channels object is kept in the console, so channels cannot be GC'd.

When you remove console.log, the full channel object will properly be GC'd, because there are no other references to it.

Rob W
  • 341,306
  • 83
  • 791
  • 678
  • 1
    thanks for additional clarity. I didn't think of the console.log. So, if I were to keep a reference to the above object "channels" in a closure, I assume that, the memory will be garbage collected as soon as the reference to the _closure_ is released ? Am I right? – Karthik Mar 16 '12 at 06:42
0

They should be, yes, because there is no more reference to that channels object nor the closure that contains it.

GC is mostly dependent on the browser that implements it, though, so there's no guarantee it'll actually be done. deleteing each element is overkill, though.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Javascript has its own garbage collector implemented by the browser's engine (v8 or whatever). You don't have to deallocate references. Once the root goes out of scope, they will all be eligible for gc.