math.random between two numbers

Generating a random number between two numbers using Math.random() in JavaScript

If you want to generate a random number between two specified numbers, you can use the Math.random() method in JavaScript. This method returns a random number between 0 (inclusive) and 1 (exclusive).

Here is an example:

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;

var randomNumber = getRandomNumber(1, 10);
console.log(randomNumber); // prints a random integer between 1 and 10 (inclusive)


In the getRandomNumber function, we first calculate the difference between the two numbers (max - min + 1) and multiply it with the result of Math.random(). This gives us a random number between 0 and the difference.

We then add the minimum value to this number to shift it within the desired range. Finally, we use Math.floor() to round down to the nearest integer.

The result is a random integer between the minimum and maximum values (inclusive).

Alternative Approach

You can also use the following approach:

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

This approach calculates a random number between 0 and the difference, adds it to the minimum value, and rounds down to the nearest integer in one step.

Both approaches are valid and will give you a random number between the specified range.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]