Generate Random Numbers in JavaScript
Complete code tutorial with examples and best practices
[ Code Example - Quick Summary ]
Language: JavaScript
What: Generate random numbers in JavaScript using <code>Math.random()</code> for general purposes or <code>crypto.getRandomValues()</code> for cryptographically secure random numbers.
Try it: Use our interactive Numbers generator or integrate this code into your JavaScript application.
Generate random numbers in JavaScript using Math.random() for general purposes or crypto.getRandomValues() for cryptographically secure random numbers.
Looking for other languages? Check our code examples in
PHP
,
Python
,
Java
,
C#
,
C++
,
Ruby
and
Go
or use our interactive web generator.
JavaScript Code Example
// Generate a random number between 1 and 100
const randomNumber = Math.floor(Math.random() * 100) + 1;
console.log(randomNumber); // Example output: 42
// Generate multiple random numbers
const numbers = Array.from({ length: 10 }, () =>
Math.floor(Math.random() * 100) + 1
);
console.log(numbers);
// Example output: [23, 7, 91, 45, 12, 68, 3, 89, 54, 31]
// Generate cryptographically secure random number
const secureRandom = () => {
const array = new Uint32Array(1);
crypto.getRandomValues(array);
return array[0] / (0xFFFFFFFF + 1); // Normalize to 0-1
};
const secureNumber = Math.floor(secureRandom() * 100) + 1;
console.log(secureNumber); // Example: 67
// Random decimal between 0 and 100
const randomFloat = (Math.random() * 100).toFixed(2);
console.log(randomFloat); // Example: 42.17
[EXPLANATION]
Math.random() returns a decimal between 0 (inclusive) and 1 (exclusive). Multiply by your range and use Math.floor() to get integers. For security-critical applications (tokens, cryptography), use crypto.getRandomValues() which provides cryptographically strong random values.
Expected Output
42 [23, 7, 91, 45, 12, 68, 3, 89, 54, 31] 67 42.17
Common Use Cases
- Browser-based games and interactive applications
- Random UI animations and effects
- Data visualization with random datasets
- Client-side form validation testing
- Random selection from arrays (shuffle algorithms)
- Generating temporary IDs or cache-busting tokens
Important Notes
-
Math.random()is NOT cryptographically secure -
Use
crypto.getRandomValues()for security tokens -
cryptois available in modern browsers and Node.js -
For Node.js, import crypto:
const crypto = require("crypto")
Try Our Interactive Generator
Don't want to write code? Use our free web-based Numbers generator with instant results.
TRY NUMBERS GENERATOR →Other Programming Languages
View Numbers generation code examples in PHP
View Numbers generation code examples in Python
View Numbers generation code examples in Java
View Numbers generation code examples in C#
View Numbers generation code examples in C++
View Numbers generation code examples in Ruby
View Numbers generation code examples in Go