JavaScript JavaScript Basics Working With Numbers The Random Challenge Solution

Used a different code, same output...

Checkout my code which does the exact same thing except it's way shorter and easier:

var no1=prompt("Type a Number *****");
var no2=Math.ceil(Math.random()*no1);
alert("Random number until "+no1+" is "+no2);

He's rounding down and adding 1, I'm rounding up and not adding anything. Same pinch. Tested out 1 to 2 20 times and never gave me an incorrect output. So... What was the need for the +1...? And in the the video once the output between 1 and 6 is 6 which is incorrect?

Anyway, just wanted to point this lil bit of trivia out. Thanks.

Moderator edited: Profanity removed from code and markdown added so that the code properly renders in the forums.

Jennifer Nordell
Jennifer Nordell
Treehouse Moderator

Hi there, Siddhant Gandhi! I added some markdown to your code, but also removed some profanity. Please note that posting profanity on the forums may violate the Code of Conduct.

1 Answer

Jennifer Nordell
Jennifer Nordell
Treehouse Moderator

Hi there, Siddhant Gandhi ! The problem with your version is that it isn't exactly the same. I know it looks that way and you say you ran it around twenty times. The problem is that it is possible (though highly unlikely) that JavaScript could roll a pure 0 with no decimal point. In that case, you would suddenly have a zero show up. Keep in mind, that it may have to do it thousands or even millions of times, but eventually, it will show up. This isn't as big of a problem in this particular example, but in other programs could potentially cause major bugs or even crash your app.

Hope this helps! :sparkles: