Better Programming

Advice for programmers.

Follow publication

Member-only story

How To Obtain Random Numbers Within a Range Using JavaScript

Code & Coins
Better Programming
Published in
2 min readMar 30, 2021
Dice
Photo by Edge2Edge Media on Unsplash.

There was a recent feature request at work that called for picking a random number to represent an index for an array of objects. We needed this logic to create a new, smaller collection of randomly selected items from the original array.

In this article, I’ll talk about how to use Math.random() to generate a random number between two numbers.

“The Math.random() function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range — which you can then scale to your desired range.” — MDN Web Docs

Below is a function that finds a random number between two arguments (min and max):

const randomNumber = (min, max) => { 
//Use below if final number doesn't need to be whole number
//return Math.random() * (max - min) + min;
return Math.floor(Math.random() * (max - min) + min);
}

Assuming min and max are whole numbers, all we need to do is multiply our random number by the difference between them plus the min. If you want the returned number to be a whole number, you simply use Math.floor() to round the generated number. Since Math.random generates a number between 0 and 1, if not rounded, the final result may not be a whole number.

Are the min and max Potential Outcomes?

In my case, I needed the min and max to be eligible for the randomization. As of now, our function does not include them. All you need to do is add 1 to max — min.

Math.floor(Math.random() * (max - min + 1) + min);

What if the Arguments Are Mixed?

To compensate for a case where the first argument is greater than the second, you can simply reassign the values used in the final function:

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Code & Coins
Code & Coins

Written by Code & Coins

Blogging about software 👨🏻‍💻 and money 💰 https://linktr.ee/mattcroak

Responses (3)

Write a response