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 trial

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

Colin Sygiel
Colin Sygiel
5,249 Points

Do we need to store the function in a variable? I was able to complete this by writing the function to the page directly

function randomNumber(upper) {
return Math.floor( Math.random() * upper ) + 1;
}

var counter = 0;
while (counter < 100) {
document.write(randomNumber(10));
counter += 1;
}

1 Answer

Sebastian Karg
Sebastian Karg
28,705 Points

Hi Colin,

your example is working, but there are some reasons why it is best practise to store the function in a variable.

  1. There is no possibility to add a space between the numbers to separate them or concatenate it to a string.
  2. Thinking of doing something else with your random number instead of only printing it out, like doing some math everytime your loop is running, it's easier to handel when stored inside a variable.
Colin Sygiel
Colin Sygiel
5,249 Points

Excellent! Thanks for the tips, Sebastian :)