How to create a secure random number using JavaScript?
October 13, 2020

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];


// 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);


// 0.8196058019110015

Step 3: Multiply with 10 to remove the fraction.

cryptoRandom3 = cryptoRandom2 * 10;


// 8.175500582013163

Step 4: Use Math.floor to get single digit random number.


// 8

NOTE: If you run the code chunks separately then you will get a different number each time. 


Leave a Reply

Most Read

#1 How to set opacity or transparency using CSS? #2 Pagination in CSS with multiple examples #3 How to check if radio button is checked or not using JavaScript? #4 How to make HTML form interactive and using CSS? #5 How to uninstall Cocoapods from the Mac OS? #6 How to add Read More Read Less Button using JavaScript?

Recently Posted

Feb 24 WordPress get_posts Examples Feb 24 How to modify the latest post array using get_posts() in WordPress? Feb 22 WordPress: How to get ACF field values from another post? Feb 22 WordPress: How to print ACF repeater field values? Feb 22 WordPress: How to print ACF array field values? Feb 21 WordPress: How to get field values in Advanced Custom Fields?

You might also like these

Reverse a String in JavaScriptJavaScriptHow to Recognize an Array in JavaScript?JavaScriptThe Difference Between Arrays and Objects in JavaScriptJavaScriptFor In Loop in Swift for BeginnersSwiftThe Drupal flowDrupalHow to Create a Copy of a Table in SQL and MySQL?SQL/MySQL3 Types of Arrays in PHPPHPHow to create a link tag button using CSS?CSSHow to vertically and horizontally align text and image block (without flex or grid) in CSS?CSSHow to overwrite file contents with new content in PHP?PHPSQL ANY OperatorSQL/MySQLWhat Does Host-Based Intrusion Detection System (HIDS) Mean and What Are Some Advantages Over NIDS?Misc