DEV Community

Discussion on: Why you should stop declaring variables inside a for loop (especially in JavaScript)

Collapse
 
maixuanhan profile image
Han Mai

Sorry. No way! Please research JS GC again.
When you assign global variable logString to the new value, you implicitly leave the old value as 'garbage' waiting for being collected. Same thing happen when you use the variable as a local one, after each iteration, the stack variable is revoked, leave the immutable string object as garbage waiting for being collected. Even if you use global, you leak the last string, leave it unused and still have reference to it hence the GC cannot detects it.

Furthermore, your measurement method seemed to be wrong, you even didn't isolate the scenario. No way your simple script took that much memory. Your browser must have opened other pages that eating resource (like fb, messenger...) at the same time that interfered your measurement result.

I've tried your both 2 snippets, no different, even a byte.