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

127
Views
How closure causes js memory leak

Could someone explaine to me why below code does not cause any memory leaks? My understanding is variable originalThing is being used in closure unCalled and theroetically referenced by closure someMethod, hence originalThing should not be garbage collected, but i do not see memory leak at all when i was profiling it in browser.

<script>
var theThing = new Array(1000000000);
var replaceThing = function () {
  var originalThing = theThing;
 
  var unCalled = function () {
    if (originalThing)
      return originalThing
  };
  var obj = {
    longStr: new Array(1000000).join('*'),
    someMethod: function () {}
  };
};
setInterval(replaceThing, 1000);
</script>

But if i changed variable obj to theThing then it would cause memory leak, please see code below:

<script>

var theThing = new Array(1000000000);
var replaceThing = function () {
  var originalThing = theThing;
 
  var unused = function () {
    if (originalThing)
      console.log("Hi")
  };
   theThing = {
    longStr: new Array(1000000).join('*'),
     someMethod: function () {}
  };
 
};
setInterval(replaceThing, 1000);
</script>

So what difference deos it make in terms of memory leak caused by closure?

about 4 years ago · Juan Pablo Isaza
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!