Using Math.random() in JavaScript

A short guide to .ceil, .floor, and .round

Joe Cardillo
Aug 28, 2018
Medium suggest adding a photo to your posts, so here is a photo by Tim Johnson on Unsplash, though it has nothing to do with the Math.random() function.

In JavaScript, to get a random number between 0 and 1, use the Math.random() function.

console.log(Math.random())
0.5408145050563944

If you want a random number between 1 and 10, multiply the results of Math.random by 10, then round up or down.

Use .floor to round down to a whole number:

console.log(Math.floor(Math.random() * 10))

Use .ceil to round up to a whole number:

console.log(Math.ceil(Math.random() * 10))

Use .round to round to the nearest whole number:

console.log(Math.round(Math.random() * 10))

--

--