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

Alisa Trunczik
Alisa Trunczik
3,659 Points

My solution

Here is my solution for this challenge.

var userNumber1 = prompt('Type any number greater than 1');
var userNumber2 = prompt('Type one more number greater than 1');
userNumber1 = parseInt(userNumber1);
userNumber2 = parseInt(userNumber2);
var randomNumber = Math.floor(Math.random() * (Math.abs(userNumber1 - userNumber2) + 1) + Math.min(userNumber1, userNumber2));
document.write('<h2> Here is a random number from ' + Math.min(userNumber1, userNumber2) + ' to ' + Math.max(userNumber1, userNumber2) + ': </h2>' + randomNumber);

I'm wondering, if there is any way to make this code shorter and clearer. Or is it okay?

Thanks!

2 Answers

Yeah it looks good enough, maybe add the parseInt the vars or remove them completely, I dont think its necessary.

var userNumber1 = parseInt(prompt('Type any number greater than 1'));
var userNumber2 = parseInt(prompt('Type one more number greater than 1'));
var randomNumber = Math.floor(Math.random() * (Math.abs(userNumber1 - userNumber2) + 1) + Math.min(userNumber1, userNumber2));
document.write('<h2> Here is a random number from ' + Math.min(userNumber1, userNumber2) + ' to ' + Math.max(userNumber1, userNumber2) + ': </h2>' + randomNumber);
Alisa Trunczik
Alisa Trunczik
3,659 Points

Sergio, thanks for your feedback! This really helps.

Uros Tadic
Uros Tadic
5,167 Points
var min = prompt ("enter your first number");
var max = prompt ("enter your second number");

var random = Math.random() * (parseInt(max) - parseInt(min)) + parseInt(min);
document.write(Math.floor(random));