How to Generate Random Number Between Two Numbers in JavaScript

To generate a random number between two numbers in JavaScript, you can use the “Math.random()” function in combination with some “arithmetic operations”.

Example 1

To get the floating-point number between two numbers in JavaScript, use the below code.

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

const randomNumber = getRandomNumber(1, 10);
console.log(randomNumber);

Output

6.322200882517803

Example 2

If you want the random number to be an integer, you can use Math.floor() function to round it down.

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

This function ensures that both min and max are integers and generates an integer between min (inclusive) and max (exclusive).

function getRandomNumber(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);

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

const randomNumber = getRandomNumber(1, 10);
console.log(randomNumber);

Output

4

These functions use Math.random() in combination with arithmetic operations to generate random numbers within the specified range.

The first function returns a floating-point number, while the second returns an integer.

Leave a Comment