Skip to main content

Archive

Show more

How to generate random number within a range in javascript

how-to-generate-random-number-within-a-range-in-javascript


Question: how to generate random number within a range in javascript

Answer: This problem has been solved in two ways, both methods will give different outputs, out of which you will have to choose the method according to your need.


First: In this code output, you can also find limit values. ('12' and '30' in this example)

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

console.log(getRandomNumber(12, 30));

Output:

22


Second: You will never get the upper range value (maximum value) in this code output but you will get a lower range value (minimum).

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

console.log(getRandomNumber(12, 30));

Output:

20


We try to provide you the best content, if there is any mistake in this article or there is any mistake in code, then let us know.

Comments