Aylian Craspa
Aylian Craspa

Reputation: 466

Does self invoking anonymous function get garbage collected after it run once?

(function (){
  let x = "hy"; 
   console.log(x);
})()

so the question is that is this function get garbage collected and removed from the memory once it executed and free up the memory?

Upvotes: 0

Views: 237

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 371019

The function expression that was invoked will get garbage collected, but it won't be immediately after the function runs - it'll get GC'd only the next time the GC runs, which may well take a few seconds. (This action is mostly invisible to JavaScript, but not entirely, if you use the new WeakRef, see snippet)

const weakRef = (function (){
  // This fn below is the one we'll be examining to see when it gets GCd
  // It's not the IIFE but the behavior is probably similar enough
  const fn = () => {
    let x = "hy"; 
    console.log(x);
  };
  fn();
  return new WeakRef(fn);
})();

const t0 = Date.now();
const intervalId = setInterval(() => {
  const hasGcd = weakRef.deref() === undefined;
  console.log('hasGcd:', hasGcd, Date.now() - t0);
  if (hasGcd) {
    clearInterval(intervalId);
  }
}, 200);

The x identifier will be GC'd as well, but there's one complication: the logged expression, since it was logged, can still exist (at least as long as the console exists and doesn't get cleared - this is probably up to the implementation). If you created an object and logged it, the object would probably not be GC'd until after the page was refreshed.

Upvotes: 1

Related Questions