Generating a random number with JavaScript.

This is a short tutorial on how to generate a random integer number using JavaScript. Below, you will find a handy JavaScript function that you can use in 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 JavaScript 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 wanted a random number between 1 and 10, you would set minNum to 1 and maxNum to 10. This would return a random integer 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. This means that our function will return a random number within the range of 1-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);

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.

NB: This function is not cryptographically secure, as it uses the Math.random() method. As a result, you should not use it for security features such as passwords, lottery results or pin codes.

Hopefully, you found this guide useful!

Related: Generating random numbers with PHP.