Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

250
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda