To create a secure random number, we will use getRandomValues() method from window.crypto
Step 1: Get a random number using getRandomValues()
var cryptoRandom = window.crypto.getRandomValues(new Uint32Array(1))[0];
console.log(cryptoRandom);
// 2557767905
Step 2: Divide that number with a similar large number.
To do we need to use JavaScript pow() Method. It returns the value of x to the power of y.
After division, we will get the random number in a fraction of a zero.
var cryptoRandom2 = cryptoRandom / (Math.pow(2, 32) - 1);
console.log(cryptoRandom2);
// 0.8196058019110015
Step 3: Multiply with 10 to remove the fraction.
cryptoRandom3 = cryptoRandom2 * 10;
console.log(cryptoRandom3);
// 8.175500582013163
Step 4: Use Math.floor to get single digit random number.
console.log(Math.floor(cryptoRandom3));
// 8
NOTE: If you run the code chunks separately then you will get a different number each time.
create getRandomValues numbers random security