In this snippet, you can find a way of generating a random number between two numbers.
Here is how to do it.
With the help of the Math.random() method, you can generate random float (number with decimals) between 0 and 1.
// Logs something like this: 0.7433471138781795 // It will be different every time var rand = Math.random(); console.log(rand);
If you want to get an integer instead of a float, you should apply the Math.floor() in combination with Math.random().
So, if you need to get a random integer between 1 and 5, you should calculate it as follows:
let math = Math.floor(Math.random() * 5) + 1; console.log(math);
In this example, 1 is considered the starting number, and 5 is the number of the possible results (1 + start (5) - end (1)).
Describing Math.random()and Math.floor()¶
Math.random() is used for returning return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). It can then be scaled in line with the expected range.