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


// 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. 

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 PHP Login System using PDO Part 1: Create User Registration Page #6 How to uninstall Cocoapods from the Mac OS?

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
How to apply style to a specific child element using CSS?CSSSpecificity of attribute selectorsCSSWhat’s new in WordPress 5.5?WordPressA list of wp-cli commands to use via SSHWordPressHow to get the first element with a class name xyz using JavaScript?JavaScriptHow to use [] (square brackets) function in Envision Basic?Envision BasicHow to create rotating texts using JavaScript and CSS?CSSWhat happens when we add Numbers and Strings in JavaScript?JavaScriptHow to create a CSS full page background image?CSSGive buttons accessible namesUI/UXHow to add Google Map in WordPress using ACF?WordPressContent types in DrupalDrupal