Search code examples
javascriptgarbage-collectionself-invoking-function

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?


Solution

  • 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.