2

Would the variable in the following sample (dog) still exist after the function has finished running?

(function(){
    var dog=1;
})();

This is largely for curiosity, though it may be useful in AJAX applications with countless such variables. Not that the spare weight would break any backs, but it would bother the developer tremendously to know that he had spare variables laying around. Also, is there a name for these variables?

j08691
  • 204,283
  • 31
  • 260
  • 272
user70585
  • 1,397
  • 1
  • 14
  • 19
  • Yes and no; when the garbage collector looks to see if any references still exist for the `1` you called `dog`, it will find none and clear it, but before then or if the GC algorithm is poor then the memory will still be in use. If your code has lots of variables that don't get destroyed properly, it is said to have a "memory leak", but this won't happen in the example you've given. – Paul S. Feb 14 '14 at 00:38
  • No, `var dog` will be scoped inside the function and can be destroyed when it completes. if you omitted the `var` keyword, `dog` would be an implicit global and would in fact persist! – actual_kangaroo Feb 14 '14 at 00:44

2 Answers2

3

From the point of view of garbage collection, there is no difference between anonymous and named functions:

function dostuff(){
  var dog = {};
}

dostuff();

In your particular example, dog goes out of scope when your function ends. Since nothing else is pointing to that object, it should be garbage collected.

However, if there are inner functions, then some of the variables might be saved inside of closures and not get garbage collected;

function dostuff(){
  var dog = {name:"dog"};
  var cat = {name:"cat"};

  setInterval(function(){
     console.log(dog.name);
  }, 100);
}

In this case dog is referenced in the callback that you passed to setInterval so this reference gets preserved when dostuff exits and will not be garbage collected. As for the cat variable it depends on the implementation. Some implementation will notice that cat is not used in any inner function and will garbage collect its contents. However, some other implementations will save all the variables in scope even if only one of them is used in an inner function.

For more information, see this: How JavaScript closures are garbage collected

Community
  • 1
  • 1
hugomg
  • 68,213
  • 24
  • 160
  • 246
2

No, var dog will be scoped inside the function and can be destroyed when it completes. if you omitted the var keyword, dog would be an implicit global and would in fact persist!

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions_and_function_scope

private state of a function can also be persisted using closures

Community
  • 1
  • 1
actual_kangaroo
  • 5,971
  • 2
  • 31
  • 45