DEV Community

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

Collapse
 
technicaljohn profile image
John Holcomb

Thank you! This is exactly what I was looking to add.

I see what the OP is attempting to draw attention to: instantiating the variable every iteration seems wasteful... Of something. He drew attention to the one thing that seemed to stand out, memory. But in truth it's not that simple, as the comments have shown.

The better answer, if loop declaration us bothering you, is to put the variable declaration in a spot that it only happens once. Either in the declarative part of the if, like in the above comment, or the more verbose way of using an if to declare the variable on first run.

I suppose my question would be, how much garbage does it create if the "bad" loop were to run 1 million times? What about in a complex situation where the GC is somehow occupied, and this loop runs 1 million times?

For sure, more testing and fuzzing is needed before coming to a conclusion regarding the "bad" way.