Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialJuanpablo Villagomez
6,890 PointsQuestion about the guess var
Is it necessary to declare the guess variable outside of the statement like that in the beginning? Wouldn't it be the same to declare the var guess prompt inside of the do while loop instead? the guess variable isn't being used anywhere else in the script aside from inside of the loop
1 Answer
Henrik Hansen
23,176 PointsEven if it is possible to declare the variable inside of the loop, you should not do that because you will be declaring that variable each iteration of the loop. Declaring a variable will allocate some memory for that var, and changing the value of that var will reuse the allocated memory instead of allocating new memory every time. It might not be a problem if the loop runs 10 times, but it will be a problem at 10000x. Even if unused vars will be garbage collected, we want to avoid this and try to keep a good memory management in our code. At least in Java the garbage collection is a very costly process, and I suspect it is in Javascript as well.
In other words, declaration of variables should only be done once, and then altered later on.
john larson
16,594 PointsHenrik, I've noticed you provide consistently good, straightforward answers.
Juanpablo Villagomez
6,890 PointsJuanpablo Villagomez
6,890 PointsIt's in response to this video https://teamtreehouse.com/library/javascript-loops-arrays-and-objects/simplify-repetitive-tasks-with-loops/do-while-loops