The random method helps in generating pseudo-random numbers, since, arithmetically, generating a true random number is impossible.
We can get random numbers using Math.random() function, like this:
This function doesn’t take any arguments and will return the random float number between 0 and 1.
If we want to generate random numbers between any two numbers or up to a limit. The syntax would be different for them. For better understanding, let’s try a couple of examples.
Suppose, we want to generate a random number from 0 to 99. The syntax for providing a limit or a range is:
Keep in mind that 100 is a limit or range, not the number.
You can see that it has generated a number from 0 to 99, but, it’s a float number.
So, if we want to have a whole number and not a float number, ,we can apply a Math.floor() method over Math.random() method, like this:
That looks great!
Now, what if we do not want to have numbers from 0 to 99 or onwards but from some other number, for example, 50 to 90. First, let’s see how we can do that, and later we will see how it works.
In this syntax, 40 is the range or limit from 50 to onwards, 50 as the starting number.
In the end, if we want to build our custom random function to which we can provide two numbers (minimum and maximum) and get a random number between those two numbers. The function would be like this:
Keep in mind that the ending number or “lNum” will be excluded. In case you want to include that as well add “1” in the range, like this:
After writing this function. Let’s call it and see the results.
As you can see, we are getting random numbers from 20 to 40.