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

Łukasz Giergielewicz
Łukasz Giergielewicz
4,059 Points

Why not use Math.ceil()?

var randomNumber = Math.ceil(Math.random() * 6);

Seems to only return values between 1 and 6, is there a possibility of a failure?

2 Answers

Steven Parker
Steven Parker
231,269 Points

While it's highly unlikely, Math.random() can theoretically return zero, so your formula would return 1-6 with approximately equal likelihood, but perhaps also 0 with a far lower probability.

That's why Math.floor() is generally used instead of Math.ceil() with random formulae, since the result can be relied on to remain in the range and give each value approximately equal probability.

Doron Geyer
seal-mask
.a{fill-rule:evenodd;}techdegree
Doron Geyer
Full Stack JavaScript Techdegree Student 13,897 Points

What Steven has said above in simpler terms.

Going to break it down into steps.

Math.random(); provides values from 0(including zero) to 0.99999999999 but never 1.

Math.floor will round it down to the nearest whole number.

so if we take it mathematically. even if you get 0.9999999 as above and you * 6 you will get 5.999999 whichMath.floor will drop to 5

so your range is 0-5 the "+1" just increases the minimum from 0 to 1 and the max from 5 to 6.

with Math.ceil if you random 0 it will leave the value as zero.

which will mean that your code var randomNumber = Math.ceil(Math.random() * 6); gives you a range of 0 to 6 instead of 1 to 6 like a dice.