JavaScript Random Number explained

The Math.random() function in JavaScript generates a random decimal number between 0 (inclusive) and 1 (exclusive). To generate random numbers within a specific range, you can combine Math.random() with some additional calculations. Here are examples of generating random numbers with minimum and maximum values:

  1. Generate a random integer between a minimum and maximum value:
function getRandomInt(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

// Usage:
var randomNumber = getRandomInt(1, 10);
console.log(randomNumber);

In this example, the getRandomInt function takes a minimum and maximum value as parameters and returns a random integer within that range (inclusive).

  1. Generate a random decimal number between a minimum and maximum value:
function getRandomFloat(min, max) {
  return Math.random() * (max - min) + min;
}

// Usage:
var randomDecimal = getRandomFloat(0.5, 1.5);
console.log(randomDecimal);

In this example, the getRandomFloat function takes a minimum and maximum value as parameters and returns a random decimal number within that range.

Make sure to adjust the minimum and maximum values according to your specific requirements.