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:

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:

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:

A random integer between 1 and 1000:

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.

Facebook Comments