Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops What are Loops?

Why 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
PLUS
Ryan Field
Courses Plus Student 21,238 Points

Hi, 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.

Got it, thanks!