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?

Loops

I do not understand why you have assigned the randomNumber function to the variable randNum, when document.write(randomNumber(6) +" "); yields the same results. Thanks

3 Answers

The value of randNum isn't always 6.

Every time you run the program, randNum is assigned to a random number. The value isn't always the same!

So, a random number could be 6, but won't always be 6.

I hope this makes sense.

Happy C0D1NG! :grin:

:dizzy: ~Alex :dizzy:

The short answer is that in this case, you really don't need the variable. Generally, though, you do whichever is most readable. Say you had a lot more going on in that document.write() statement. We don't here, but if you had a lot of other things being written together, it might be easier to read using variables rather than the whole calculation for each item.

In this case, it won't change anything functionally - the document.write() is also inside the loop, so it will still calculate and print a new value every time. The calculation itself is pretty short, so the line is still pretty easy to read with the calculation inside the document.write(). In this case, you should do whichever you prefer the look of.

Enemuo Felix
Enemuo Felix
1,895 Points

Thanks for the clarification

Jerry Wu
Jerry Wu
1,845 Points

I agree with Naomi as I feel like declaring the variable randNum is redundant. It seems that using document.write(randomNumber(6) + ' ')); seems to do exactly the same thing as the video/instruction intends--it prints out completely random numbers each time the page is previewed and for each iteration of the loop.

Can you please clarify what you mean by the value isn't always the same? I am curious to know as I want to utilize best practices in JavaScript. Perhaps there may be another example as to why it is important to declare the variable?

Enemuo Felix
Enemuo Felix
1,895 Points

Katie Wood or Steven Parker Pls can you throw more light to this . Is it necessary to create the randNum variable to this?