Generate random whole numbers in JavaScript in a specific range

Generate random whole numbers in JavaScript in a specific range

To generate a random whole number in JavaScript within a specific range, you can use the following function:

function getRandomIntInclusive(min, max) {
  min = Math.ceil(min);
  max = Math.floor(max);
  return Math.floor(Math.random() * (max - min + 1)) + min; //The maximum is inclusive and the minimum is inclusive 
}

This function uses the Math.random function to generate a random number between min and max, and then uses Math.floor to round the number down to the nearest whole number.

You can then use this function like this:

let randomNumber = getRandomIntInclusive(1, 10); // returns a random whole number between 1 and 10 (inclusive)

The getRandomIntInclusive function takes two arguments, min and max, which represent the minimum and maximum values for the random number.

The function starts by using the Math.ceil function to round the min value up to the nearest whole number, and the Math.floor function to round the max value down to the nearest whole number. This is done to ensure that the generated random number is always a whole number, and that it falls within the specified range.

Next, the function generates a random number between min and max using the Math.random function. This function returns a random number between 0 and 1, so we multiply it by (max - min + 1) to scale it up to the desired range. Finally, we add min to the result to shift it up to the correct range, and use the Math.floor function to round it down to the nearest whole number.


✋If you have any questions about this article, ask them in our GitHub Discussions 👈 community. You can also Gitter

❤️ Like our page and subscribe to our feed for updates!

Find a list of emojis to copy and paste