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 trialApril Ehrlich
4,164 PointsWhy do we need to create a variable within the while loop? Why not write function directly to document.write?
Hi, I was wondering why the code needs to look like this:
var counter = 0;
while ( counter < 10) {
var randNum = randomNumber(6);
document.write(randNum + ' ');
counter +=1;
}
Why do we have to create the randNumb variable? Couldn't we just write the function directly to document.write, like this:
var counter = 0;
while ( counter < 10) {
document.write(randNumber(6) + ' ');
counter +=1;
}
I'm sure this harkens back to the conditional statements JS video, but I'm wondering about it now.
2 Answers
Ryan Field
Courses Plus Student 21,242 PointsHi, April. The reason they teach you this way is because this is normally how you use loops. You won't usually write something to the page during every pass of a loop--you'll more likely be iterating through arrays and such extracting or adding values.
For this particular exercise, you could write to the page each time since the end result is the same, but normally you'll want to get all the data you need first, and then do something with it, whether that's appending text to a div or firing off an AJAX call.
April Ehrlich
4,164 PointsGot it, thanks!