2

I was wondering how garbage collection works with functions. With objects, the references are pretty simple and form a tree easily. Is this the same for functions? For example:

(function() {
  let b = 2;
  let c = 3;
  window.a = function() {
    console.log(b + c);
  }
})();

a(); //prints 5

In this case, b and c are not garbage collected because a has references to them? Is this true?

1 Answers1

2

According to the specification, function objects hold an internal property pointing to the surrounding environment record, which is the place were variable values are stored. How the engine represents that in memory is up to the engine, but as long as a function object can be accessed the environment record must be known, and as such it can't be viable for garbage collection.

In this case, b and c are not garbage collected because a has references to them? Is this true?

Under the assumption that engines actually represent environment records on the heap and do garbage collection (which both are very reasonable assumptions) yes.

Under some conditions, e.g. if a variable is not accessed or is a constant, it would be a possible optimization for the engine to not store the variable's value at all:

 function unoptimized() {
   const unchanged = 1;
   let unused = 0;
   return () => unchanged;
 }

 /* could be optimized to (very simplified) */
const _inner = () => 1;
function optimized() { return _inner; }
   
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151