Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript - Garbage collection after function calls

I had some reads about garbage collection in JavaScript, according to them, local variables of functions are collected after the function returned (except for the cyclical references that need breaking circles for the GC to work).

What I'm trying to understand is, what does "function returned" in this context mean?

Does it mean:

  1. The function has to return values.

    or simply:

  2. The function call has ended.

Common sense (according to me at least) suggests 2), but in the case I'm wrong:

  • What about functions that don't return values?
  • Should I add an empty return; to the functions that don't return anything to make the garbage collector do its job?
like image 713
heytools Avatar asked Jul 06 '26 08:07

heytools


1 Answers

Functions that don't contain a return statement implicitly return undefined. So a function "ending" and "returning" are the same thing.

Concerning garbage collection, keep in mind that local variables are not collected immediately after functions return; they can just become eligible for garbage collection at that point. The garbage collector runs whenever the browser considers it must run, or believes it can run without affecting visible performance much (and that's implementation-dependent).

like image 174
bfavaretto Avatar answered Jul 07 '26 23:07

bfavaretto



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!