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 Basics (Retired) Working With Numbers The Random Challenge Solution

Why does he create an extra variable?

Why does he create the topNumber variable when you could just do like this?:

var userNumber = prompt("Write a number");

var result = Math.floor ( Math.random() * parseInt(userNumber) + 1 );

Is there a reason for that or does he just want to be super-clear?

2 Answers

Steven Parker
Steven Parker
216,148 Points

Breaking the process into steps at this point probably doesn't seem to make a big difference.

But as the lesson progresses, the formula is enhanced; and keeping the input and conversion operations separate from the calculation will make understanding the formula a lot less complicated.

I have done something similar. Rather than creating an extra variable, to make things simpler i have just added "parseInt" at the beginning when prompting for an input.

var topNunber = parseInt ( prompt ("Please provide a number.") );

Can this be one of the simpler way.

Steven Parker
Steven Parker
216,148 Points

That's fine if you won't need the original answer. But in a more sophisticated program, you might detect if the numeric conversion worked correctly, and if not you might want to include the original answer in an a error message.