0

I'm curious as to when garbage collection happens in javascript (specifically on node.js).

(async() => {
  let data = await getBigBlobFile()
  const name = data.name

  data = null //is this necessary?

  longAsyncFunction(name, (err, res) => {
    if (err) throw err
    return res
  })
})()

In this pseudo-code, is it necessary to manually set null on data?

I'm not sure if GC happens when the reference is out of block or is it enough for the compiler that 'data' is not used again until the end of the block? I need it to be released while the async function is running.
I've seen comments saying modern engines do this automatically but I can't seem to find anything to back this up.

1 Answer 1

2

For the most part, variables are garbage collected when the scope of that variable is no longer needed. Setting variables to null is not necessary, and it actually does not have the same meaning that null does in C/C++.

It is important to understand variable scope in JavaScript, as closures play a major role in a lot of design patterns. NodeJS is based on Google's V8 engine, which does indeed handle all GC automatically.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the references. I'll try to look into them :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.