Generate random number between two numbers in JavaScript

Mirgorod picture Mirgorod · Feb 10, 2011 · Viewed 1.6M times · Source

Is there a way to generate a random number in a specified range (e.g. from 1 to 6: 1, 2, 3, 4, 5, or 6) in JavaScript?

Answer

Francisc picture Francisc · Aug 29, 2011
function randomIntFromInterval(min, max) { // min and max included 
  return Math.floor(Math.random() * (max - min + 1) + min);
}

What it does "extra" is it allows random intervals that do not start with 1. So you can get a random number from 10 to 15 for example. Flexibility.