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

249
Visualizações
JS Garbage Collection: Are declared functions (which are not called) garbage collected?

I am new to memory management in JS, so please pardon if this is a dumb question.

Suppose I have a component with three functions defined and a switch case statement which calls only one function depending on the case matched. Will the other two functions occupy the memory or they are garbage collected once the switch statement is executed?


function funcA() {};
function funcB() {};
function funcC() {};

switch(type) {
    case 'funcA':
        funcA();
        break;
    case 'funcB':
        funcB();
        break;
    case 'funcC':
        funcC();
        break;
}
almost 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

If defined inside a function scope and not at the top-level of the document, any local variables referenced only inside that scope (including function definitions) will be garbage collected at some point after the function finishes executing.

You can verify this using FinalizationRegistry like so:

function memoryExperiment(type) {
    function funcA() {};
    function funcB() {};
    function funcC() {};
    
    const registry = new FinalizationRegistry((heldValue) => {
        console.log(`Garbage collected ${heldValue}`)
    });
    registry.register(funcA, "funcA")
    registry.register(funcB, "funcB")
    registry.register(funcC, "funcC")

    switch(type) {
        case 'funcA':
            funcA();
            break;
        case 'funcB':
            funcB();
            break;
        case 'funcC':
            funcC();
            break;
    }

    return registry
}

const registry = memoryExperiment('funcA')

A message is logged for all three functions indicating they were garbage collected.

It is difficult to predict exactly when they will be collected as the garbage collection algorithm makes decisions based on various factors, but in my testing on an otherwise blank html file in Chrome it's usually after a few seconds.

almost 4 years ago · Santiago Trujillo Relatório
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