JavaScript Tip: get a Random Number between two Integers

In JavaScript, we can get a Random number; however, this number is between 0 and 1 which is not very useful when we want to work with integers.
For example, executing the random method of the Math Object we can get something like this:

Math.random(); // 0.7427427755721524
Math.random(); // 0.001514993949523702
Math.random(); // 0.4938488937880676

Many languages like PHP have a random function that takes two integers as parameters and returns a number in the range of the value of the two integers. (The range include the parameters). For example, we can do this in PHP:

rand(10,20); //12
rand(10,20); //18
rand(10,20); //17

We can emulate this with the following function:

function randomFromTo(from, to){
   return Math.floor(Math.random() * (to - from + 1) + from);

randomFromTo(10,20);  //18
randomFromTo(10,20);  //10
randomFromTo(10,20);  //15
randomFromTo(10,20);  //20

What about using it as part of the JavaScript Core?

Most of developers do not recommend extending the built-in objects because it can create confusion among developers working on the same project. However, there are a lot of frameworks that extend the built-in object like Prototype. The way to do it is by using the prototype object that is part of all objects created in JavaScript. Example:

  Math.randomFromTo = function(from, to){
    return Math.floor(Math.random() * (to - from + 1) + from);

With this piece of code we can call the method from the Math Object like this:

Math.randomFromTo(100,1000) //950

How to get a random item from an array

If you want to go beyond, you can add a new method to the Array Object which would return a random element. Example:

if (!Array.prototype.random) {
  Array.prototype.random = function() {
    return this[Math.randomFromTo(0, this.length - 1)];

Now we can use the randomItem method like this:

[13, 5, 86, 11, 15].random(); //11

This would return one of the items of the array randomly.

Teylor Feliz
Teylor Feliz

Teylor is a seasoned generalist that enjoys learning new things. He has over 20 years of experience wearing different hats that include software engineer, UX designer, full-stack developer, web designer, data analyst, database administrator, and others. He is the founder of Haketi, a small firm that provides services in design, development, and consulting.

Over the last ten years, he has taught hundreds of students at an undergraduate and graduate levels. He loves teaching and mentoring new designers and developers to navigate the rapid changing field of UX design and engineering.

Articles: 182