Generate random numbers in JavaScript by Cules Coding

Generate random numbers in JavaScript

In this blog, you will learn how to generate random numbers in javascript.

There is no straightforward way to generate a random number. You have to use a little trick.

Math.random function gives us a random number between 0 and 1.

1const getRandomNum = () => {
2 reutrn Math.random()
3}
4
5console.log(getRandomNum())
6console.log(getRandomNum())
7console.log(getRandomNum())
8console.log(getRandomNum())
9
10// output
11// 0.4656524910632813
12// 0.36946529666025185
13// 0.93309610877532
14// 0.6869999317373736

That's not what you want. You need an integer. To get an integer you need to multiply the random number with another number. And then you have to floor the value.

Get a random integer

1const random = Math.random
2const floor = Math.floor
3
4const getRandomNum = () => {
5 return floor(random() * 10)
6}
7
8setInterval(() => {
9 const num = getRandomNum()
10
11 console.log(num)
12}, 500)
13
14// Output:
15// 2
16// 5
17// 1
18// 9
19// 1
20// 7
21// 6
22// 0
23// 7
24// 3
25// 4
26// 8
27// 2
28// 2
29// 4
30// 5
31// 5
32// 0

By multiplying a number you have set an upper limit for the random number. We have floored the value because we don't want a floating-point number. Math.floor function gives us this

18.343487294263 --> 8
23.37294263 --> 3

Notice that we never get 10 as our random number. Because that is our limit. To include 10, just add 1 to the number.

Get a random integer in a range

Let's see how we can get a random number between 10 and 20

1const random = Math.random
2const floor = Math.floor
3
4const getRandomNumInRange = (min, max) => {
5 return floor(random() * (max - min + 1)) + min
6}
7
8setInterval(() => {
9 const num = getRandomNumInRange(10, 20)
10
11 console.log(num)
12}, 500)
13
14// output:
15// 11
16// 13
17// 14
18// 20
19// 13
20// 13
21// 10
22// 16
23// 17
24// 10
25// 16

Explanation: Now we need something between two numbers. So, we generate random numbers up to the difference of our range. In our case, it will be

1difference = 10
2random numbers = [
3 2,3,4,6,10 ...
4]

Then we add our minimum number with a random number. And that number definitely will be in the range.

You can write the code in one line.

1const getRandomInt = (min, max) =>
2 Math.floor(Math.random() * (max - min + 1)) + min

That's how we get a random number in a range.

Shameless Plug

I have made an Xbox landing page clone with React and Styled components. I hope you will enjoy it. Please consider like this video and subscribe to my channel.

That's it for this blog. I have tried to explain things simply. If you get stuck, you can ask me questions.

Contacts

Blogs you might want to read:

Videos might you might want to watch:

Previous PostBuild a random password generator app with vanilla JavaScript
Next PostEverything you need to know about Javascript Destructuring