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

Quinton Dobbs
Quinton Dobbs
5,149 Points

My solution works, but can it be improved?

I think my solution it pretty good and it works well. But, can I do it in less lines or with less characters?

var userNum1 = parseInt(prompt('Name a number'));
var userNum2 = parseInt(prompt('Name a another number greater than the last'));
var finalNum = Math.floor(Math.random() * (userNum2 - userNum1 + 1)) + userNum1;
parseInt(finalNum);
document.write('Your number is ' + finalNum);

4 Answers

Your numbers are not random. Something simple that does what the teacher wants would be;

var pick = prompt("Pick a number any number"); alert("Youve chosen " + pick + " lets see if you got it!");

var math = Math.floor(Math.random() * 6) + 1; alert(math);

document.write("Computer picked " + math + " You picked " + pick);


Run that and you'll see what I mean

Aaron Price
Aaron Price
5,974 Points

Looks like he gives an official solution in the very next video, but yours is honestly not bad at all.

Quinton Dobbs
Quinton Dobbs
5,149 Points

Awesome! Appreciate the positive feedback!

Sam Donald
Sam Donald
36,305 Points
  • Because you are running parseInt() over the prompts you don't need to apply it to finalNum.

  • You can see your userNum1 and userNum2 has a bunch of repeated code. We can fix that with a function.

  • The function also gives us a nice opportunity to introduce a conditional number checker with isNaN().

var num1 = getNumber("Enter a number");
var num2 = getNumber("Enter another number");
var number = Math.floor(Math.random() * (num2 - num1 + 1)) + num1;

function getNumber(msg) {
    var value = parseInt(prompt(msg));
    if(isNaN(value)) {
        return getNumber("That's not a number. Please enter a number");
    }
    return value;
}

document.write("Your number is "+number);