DEV Community

Randy Rivera
Randy Rivera

Posted on • Edited on

Generate Random Whole Numbers within a Range

function randomRange(myMin, myMax) {
  return Math.floor(Math.random() * (myMax - myMin + 1)) + myMin
}

console.log(randomRange(1, 9));
Enter fullscreen mode Exit fullscreen mode
// If the values were myMin = 1, myMax= 9, one result could be the following:

// Math.random() = 0.27934406917448573
// (myMax - myMin + 1) = 9 - 1 + 1 -> 9
//  0.27934406917448573 * 9 = 2.51409662257 
// 2.51409662257 + 1 = 3.51409662257
// Math.floor(3.51409662257) = 3
Enter fullscreen mode Exit fullscreen mode
  • 1. Randomizing a decimal, then taking 9 - 1 which is 8 then adding it to + 1 which is 9.
  • 2. Then taking the randomized decimal that it gave us and multiply it by 9.
  • 3. The result of that multiplication will then + 1;
  • 4. Then result will be “rounded” to the largest integer less than or equal to it (eg: 3.5 would result in 3) which in this case will be.

Top comments (0)