DEV Community

Cover image for Math.random() Use Cases
Heggy Castaneda
Heggy Castaneda

Posted on

Math.random() Use Cases

Math.random() used when generating random numbers of a range. Many times Math.random() used in conjunction with another method such as Math.floor() or user input to get a whole number at the end.

  • case 1) Generate whole number ranging from [0, 3] (numbers from 0 to 3 both ends inclusive).

    • Math.random() generates pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1).
    • To only get whole numbers, we use Math.floor() to round down.
// multiply by 4; Math.random()'s upper end, 4 is exclusive
const randomNumber = Math.floor(Math.random() * 4);
  • case 2) Generate whole number [1, 6](numbers from 1 to 6 both ends inclusive).

    • Add one to randomly generated numbers.
    • Math.ceil() may look simple to use here but it will generate 0 as a result if Math.random() give 0.
// => `[0, 6]`
Math.ceil(Math.random() * 6)
  • We want [1,6]
// => `[1, 6]`
//  Math.random() * 6 => [0, 5] then add one to each => [1, 6]
Math.floor(Math.random() * 6 + 1)
  • case 3) Generate whole number from 1 to user's favorite whole number.
const userFavNum = 5;
// Math.random() * 5 => [0, 4] then add one to each => [1, 5]
Math.floor((Math.random() * userFavNum) + 1)

Top comments (1)