In the example above, we multiplied Math.random() by 10 to get a number between 0 and 10, and we added 1 to get a number between 1 and 10. Finally, we used the floor() function that always rounds down and returns the largest integer less than or equal to a given number.
Creating A Random Number Generator Function
To make our random number generator more reusable, we can create a function that accepts a range and returns a random number within that range. Here is an example of a random number generator function:
In the example above, the getRandomNumber() function accepts two parameters, min and max, representing the range’s minimum and maximum values. The function calculates a random number within the field by subtracting the minimum from the maximum to get the size of the range, then multiplying Math.random() by the size of the range, and finally adding the minimum to the result.
Using The Random Number Generator Function
To use the random number generator function, we call it and pass in the minimum and maximum values of the range. Here is an example:
In the example above, we called the getRandomNumber() function by passing the minimum and maximum values as 1 and 10. The function then returns a random number between 1 and 10, which we logged into the console.