DEV Community

loading...

JavaScript Random Function Explained

acroynon profile image Adam Roynon ・2 min read

The random function in JavaScript is used to generate randomly generated numbers while programming. Random generation can be used for generating random numbers, procedural levels for games, and much more. It can also be used to pick certain routes through code based on random selection rather than the result of user interaction.

The random function is within the 'Math' object in JavaScript. When calling the random function a number between 0 and 0.999 recurring will be returned. A new random number will be returned each time the method is called, or each time the page is reloaded. The below code snippet show setting the return value to a variable called 'ran', whose value will be a random number between 0 and 0.9 recurring.

var ran = Math.random();
Enter fullscreen mode Exit fullscreen mode

You can also change the numbers that are randomly generated. The below code shows multiplying the return result of the random function by the number 6. This will generate a decimal point number from 0 to 5.9 recurring. This is because the lowest number generated from the random function is 0 and the highest number is 0.9. 0 times 6 equals 0. 0.9 times by 6 is 5.9. This is how the below code generates numbers from 0 to 5.9.

var ran = Math.random() * 6;
Enter fullscreen mode Exit fullscreen mode

The minimum number generated can also be changed. The below algorithm shows how to generate a random number between 1 and 10. This is because we are multiplying the random function by 9, which returns a result between 0 and 9. Then we add the number 1 to the result. This results in a function between 1 and 10. The last line then rounds the number, to remove the decimal points. This algorithm can be quite difficult to understand so read it through and play around with the code yourself.

var max = 10;
var min = 1;

var value = Math.random() * (max-min) + min;
value = Math.round(value);
Enter fullscreen mode Exit fullscreen mode

The random function returns a number between 0 and 0.9 recurring. Using a surrounding algorithm, a number between any minimum and maximum number can be randomly generated. The above algorithm can be difficult to understand initially, so read it through and play around with it until you understand how it works.

This article was originally posted on my website: https://acroynon.com/

Discussion (0)

pic
Editor guide