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

247
Views
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 answers
Answer question

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 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!