Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

154
Views
Is important to set 'var = null' in the end of lexical scope?

I was reading this post that clarified almost everything about scopes, leaving only this doubt:

If lexical scopes generate a new environment on each run and store their information, in an environment where code runs frequently, you need to declare var_of_scope = null at the end of the scope to free memory or JavaScript recognizes this automatically if not are there elements that refer to the environment?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

No, that is almost never necessary.

Javascript uses garbage collection. When no values in any scope reference a value stored in memory, it is removed during the next run of garbage collector.

In the situation you describe:

function foo() {
  let data = "some data here"
  // do stuff with data
  data = null
}

Setting the null here is not helpful. It does remove all references the previous value of data, but since the scope will end when the function ends, all local variables will be discarded along with it anyway.


In fact, this would prevent you from using the const keyword, which is a very very good thing to use. All your variables should be const by default, and you should change them to let only if you really need to assign them after initialization.

This is better:

function foo() {
  const data = "some data here"
  // do stuff with data
}

In general, you just don't have to worry about this. It's not easy to leak memory in javascript like it is in a language like C. It's possible but as long your following most best practices you'll probably be fine.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!