Yogesh Chauhan's Blog

How to create a secure random number using JavaScript?

in JavaScript on 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];

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. 


Most Read

#1 Solution to the error “Visual Studio Code can’t be opened because Apple cannot check it for malicious software” #2 How to add Read More Read Less Button using JavaScript? #3 How to check if radio button is checked or not using JavaScript? #4 Solution to “TypeError: ‘x’ is not iterable” in Angular 9 #5 How to uninstall Cocoapods from the Mac OS? #6 PHP Login System using PDO Part 1: Create User Registration Page

Recently Posted

#Apr 8 JSON.stringify() in JavaScript #Apr 7 Middleware in NextJS #Jan 17 4 advanced ways to search Colleague #Jan 16 Colleague UI Basics: The Search Area #Jan 16 Colleague UI Basics: The Context Area #Jan 16 Colleague UI Basics: Accessing the user interface
You might also like these
A few HTML coding standards from WordPressHTMLHow to merge arrays in JavaScript?JavaScriptHow to use GROUPING SETS to boost GROUP BY queries in Postgres?PostgresWhat’s the difference between variables in CSS and SCSS (Sass)?CSSWordPress: How to print ACF array field values?WordPressWhat does it mean by Continuous Integration, Continuous Delivery and Continuous Deployment?MiscellaneousHow to create a secure random number using JavaScript?JavaScriptSolution to Precision Problem in JavaScript NumbersJavaScriptHow to reference an aliased column in the WHERE clause?SQL/MySQLThe SQL EXISTS OperatorSQL/MySQLHow to get ACF values from custom post type?WordPressSome interesting HTML Input Attributes to rememberHTML