Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

128
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda