How to generate a random number with JavaScript.

In this tutorial, we will show you how to generate a random number using JavaScript.

We will also provide you with a useful JavaScript function that you can copy and paste into your project.

Take a look at the following function:

/**
 * Custom JavaScript function that generates a random integer number
 * between two numbers.
 *
 * @param minNum The lowest value that should be returned.
 * @param maxNum The highest value that should be returned.
 * @returns {number}
 */
function random_int(minNum, maxNum){
    var num = Math.floor(Math.random() * (maxNum - minNum + 1) + minNum);
    return num;
}

The function above will generate a random integer between two given numbers.

It has two parameters:

  1. minNum: This is the lowest value that should be returned.
  2. maxNum: This is the highest value that should be returned.

For example, if you want a random number between 1 and 10, then you will need to set minNum to 1 and maxNum to 10. This will return a random number within the range of 1–10.

Take a look at the following examples, which show the function being used.

In the code below, we generated a random number between 1 and 100:

//Between 1 and 100
var num = random_int(1, 100);
alert('Random number was: ' + num);

As you can see, we set the first parameter (minNum) to 1 and the second parameter (maxNum) to 100.

Generating a random number between 1 and 5:

//Random int between 1 and 5
var num = random_int(1, 5);
alert('Random number was: ' + num);

Generating a random integer between 1 and 1000:

//Random int between 1 and 1000
var num = random_int(1, 1000);
alert('Random number was: ' + num);

As you can see, this function is pretty straight-forward and easy to use.

Simply adjust the min and max values to suit your requirements.

Please note that this function is not cryptographically secure as it uses the Math.random() method.

Therefore, you should never use it for security features such as passwords, lottery results, or pin codes.

Related: Generating random numbers with PHP.