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?

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,704 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 :)