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 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
229,644 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.

Shreemangal Sethi
seal-mask
.a{fill-rule:evenodd;}techdegree
Shreemangal Sethi
Full Stack JavaScript Techdegree Student 15,552 Points

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
229,644 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.