JavaScript(JS) JS generate a random number between two numbers

To generate a random number between two given numbers using JavaScript, you can use the following code:

refer to‮tfigi:‬idea.com
function randomInRange(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Example usage:
console.log(randomInRange(1, 10)); // Output: A random integer between 1 and 10, inclusive

In this code, we define a function called randomInRange that takes in two parameters, min and max, representing the minimum and maximum values of the range.

We use the Math.random() method to generate a random number between 0 and 1, then multiply it by the difference between max and min plus 1 to get a random number between 0 and the range size, and then add min to shift the random number to the desired range. Finally, we use Math.floor() to round the result down to the nearest integer.

To use the function, you can call it with the desired range as shown in the example usage. This will print a random integer between the given min and max values, inclusive, to the console.