Get random integer between two numbers


Getting a random number is a fairly common problem and sometimes it's surprising that this can't be done by using a single function, maybe this recipe helps for those having forgotten the way to achieve this.


It requires some basic math, but in the end it's nothing else but this

var maximum = 20;
var minimum = 10;
Math.floor(Math.random() * (1 + maximum - minimum)) + minimum;

If you of course also create a new function:

function randomInt(minimum, maximum) {
  return Math.floor(Math.random() * ( 1 + maximum - minimum ) ) + minimum;  


Please sign-in to post a comment