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

Filip Diarra
Filip Diarra
6,647 Points

What if the first number entered was larger than the second number? Would this equation still work?

Hi there!

Here is the challenge https://teamtreehouse.com/library/javascript-basics/working-with-numbers/the-random-challenge-solution

I get how the second part of the solution works, but is this assuming that the user will always input the smaller number first? Wouldnt inputting 17 and then 4 make this not work?

Thanks!

Simon Coates
Simon Coates
28,694 Points

at a beginning level, it probably doesn't matter. Under real circumstances you might input validation, and a strategy for errors. The eternal undying rule in IT is don't trust user inputs.

3 Answers

Filip Diarra
Filip Diarra
6,647 Points

So am I right in expecting this to not work when a large number is input first?

Thanks!

Simon Coates
Simon Coates
28,694 Points

yeah, i looked at the equation and it can't be relied upon when the values are fed in the wrong order.

Tow Boon Ng
Tow Boon Ng
14,507 Points

for the second input, I used this as Prompt

var higherLimit = prompt("Choose a number greater than "+ chosenNumber);

to prompt user to enter a larger number

Michelle Harrison
Michelle Harrison
8,782 Points

I thought about that as well and I know it hasn't been covered yet (At least in the Web Development track), but I googled to see if there was a way to find the minimum and maximum number between two numbers with Javascript. There is. Math.min() for finding the minimum # Math.max() for finding the max # Here's my code and it works even if the user does put a larger number in first. I'm still having trouble understanding the math though :(

var inputOne = prompt("Enter a number, any number");
var inputTwo = prompt("Now the second number, please");
var bottomNumber = parseInt(inputOne);
var topNumber = parseInt(inputTwo);

var n1 = Math.min(bottomNumber, topNumber);
var n2 = Math.max(bottomNumber, topNumber);

var randomNumber = Math.floor(Math.random() * (n2-n1+1)) + n1;
var message = "<p>" + randomNumber + " is a number between " + n1 + " and " + n2 + ".</p>";
document.write(message);