8 C
Jaipur
Thursday, January 28, 2021

Javascript Random Number – Linux Hint

Must read

While developing a gaming website, we often need to generate random numbers. In this article, we are going to know how we can get a random in Javascript using the random method.

The random method helps in generating pseudo-random numbers, since, arithmetically, generating a true random number is impossible.

Syntax

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.

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:

function getRandomNum(sNum, lNum) {
 return Math.floor((Math.random * (lNum sNum)) + sNum)
}

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:

function getRandomNum(sNum, lNum) {
 return Math.floor((Math.random * (lNum sNum + 1 )) + sNum)
}

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.

So, these are some of the different ways to generate pseudo-random numbers in Javascript using the Math.random() method.

Conclusion

In this article, we have learned to get random numbers in Javascript and tried several techniques to get the desired results. We have also learned to make a custom function in which we can provide the range of numbers and get the random numbers between that ranges.

So, keep on learning Javascript with linuxhint.com to have a better grasp over it. Thank you!

Source link

- Advertisement -

More articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest article