skip to Main Content

hi i have a query and was unable to get exact answer. I have a below closure function

function closure() {let innerVal; return function() {innerVal = innerVal+10}}
let inst = closure();
inst();
console.log('end');

will innerVal be cleared during GC after inst() is called or not?

2

Answers


  1. I created a little demo using WeakRef

    You can run it and wait 100 seconds

    let outerRef;
    function closure() {
      let innerVal = { v: 0 }
      outerRef = new WeakRef(innerVal)
      return function() {
        innerVal = innerVal.v + 10
      }
    }
    let inst = closure();
    inst();
    console.log('end');
    
    setTimeout(() => {
      const v = outerRef.deref()
      console.log(v)
    }, 100000)

    It prints undefined in the end so the object has been garbage collected

    Login or Signup to reply.
  2. will innerVal be cleared during GC after inst() is called or not?

    It won’t be garbage collected until after the invocation. However, no garbage collection algorithm is specified in the ECMAScript language specification. So…

    • whether or not the memory will be freed before process termination, and
    • the exact timing of the action

    …depends on the specific runtime implementation: you will need to consult the documentation/source code of the runtime in question to obtain that information. You can learn more about garbage collection observability at the Memory management article on MDN.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search