DEV Community

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

curtisfenner profile image
Curtis Fenner • Edited on

I really doubt this is right at all, and this is not a good experiment to show that it is right.

1) You're not recording the heap before hand, so it's impossible to know how much has actually changed

2) You're not running multiple experiments. The garbage collector is not deterministic, so you'll get slightly different numbers each time. At the least, you should be reporting an average over many trials.

3) You're logging to the console in this experiment. Logging to the console expends huge amounts of memory and CPU which are going to make the results far too variable to be useful.

For the record, when I tried measuring the difference, I saw no difference; the amount of memory that had been used by any single run was basically random, and neither was more or less than the other.

Remember the three rules of optimization:

1) Don't.

2) Don't, yet. (Experts only)

3) Profile before optimizing. Even if this experiment showed that variables inside loops use more memory, that wouldn't justify the blanket advice to not declare variables in loops, because that's probably not where most of your program is using its memory; instead of hurting readability and violating best-practices, you should find where your program is actually wasting most of its memory.

nicolalc profile image
Nicola Author

Yes you're right, I'll keep your tips for the next time!

peq profile image
Peter Zeller

Don't wait until next time. This is harmful, bad advice. You should add a big fat disclaimer to the article that so you made mistakes here.

technicaljohn profile image
Technical John • Edited on

Please look further down the comments for a comment by Jan Hasebos. It would address your perception regarding the iterated declaration, while also respecting the variable scope of the for loop.

Really, you'd be better off saying the "bad" example is ok, while you feel the "good" example is better.

I added some thoughts below Jan to expand on this.

danielrogowski profile image

Seconding your answer.

lesha profile image
lesha 🟨⬛️

I want to buy you a beer