JavaScript Random Number Generator
Instantly generate secure, customizable random numbers for browsers & Node.js. Try our javascript code generator tools for more options.
Random Number Generator
Code Examples
// Generate random integer between min and max (inclusive)
function getRandomInt(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
// Generate random float between min and max
function getRandomFloat(min, max, decimals = 2) {
const random = Math.random() * (max - min) + min;
return parseFloat(random.toFixed(decimals));
}
// Generate array of random numbers
function generateRandomArray(min, max, count, allowDuplicates = true) {
const numbers = [];
const used = new Set();
for (let i = 0; i < count; i++) {
let number = getRandomInt(min, max);
if (!allowDuplicates) {
while (used.has(number)) {
number = getRandomInt(min, max);
}
used.add(number);
}
numbers.push(number);
}
return numbers;
}
// Usage examples
console.log(getRandomInt(1, 100)); // Random integer 1-100
console.log(getRandomFloat(0, 1, 3)); // Random float 0-1 with 3 decimals
console.log(generateRandomArray(1, 10, 5, false)); // 5 unique numbers 1-10
Usage Tips:
- • Use
Math.random()
for general purposes - • Use
crypto.getRandomValues()
for security-critical applications - • Always check for duplicates when generating unique numbers
- • Consider performance when generating large arrays
💡 If the copy button doesn't work, you can click on the code area to select all, then press Ctrl+C (Windows) or Cmd+C (Mac) to copy manually
Common Use Cases
Game Development
Dice rolls, card shuffling, random events, loot drops
Roll a 6-sided die: getRandomInt(1, 6)
Shuffle cards: generateRandomArray(1, 52, 52, false)
Random enemy spawn: getRandomInt(1, 10)
Testing & Mock Data
Generate test data, simulate user behavior, performance testing
Mock user IDs: generateRandomArray(1000, 9999, 100)
Test scores: getRandomFloat(0, 100, 1)
Random timestamps: Date.now() + getRandomInt(0, 86400000)
Security Applications
Password generation, encryption keys, secure tokens
Generate PIN: getRandomInt(1000, 9999)
Random password: generateRandomString(8, 16)
Session tokens: crypto.randomUUID()
UI/UX Design
Random colors, animations, layout variations
Random color: #${getRandomInt(0, 16777215).toString(16)}
Animation delay: getRandomFloat(0, 2, 2)
Random avatar: getRandomInt(1, 10)
Data Analysis
Sample data, statistical analysis, A/B testing
Random sample: generateRandomArray(1, 1000, 100, false)
Normal distribution: generateNormalDistribution(0, 1, 1000)
A/B test groups: getRandomInt(1, 2) === 1 ? "A" : "B"
Quick Examples
🎲 Dice Roll
Math.floor(Math.random() * 6) + 1
🎨 Random Color
'#' + Math.floor(Math.random()*16777215).toString(16)
📊 Random Array
Array.from({length: 10}, () => Math.floor(Math.random() * 100))
🔐 Random Password
Math.random().toString(36).substring(2, 15)
Algorithm Comparison
Math.random()
Built-in JavaScript random number generator
Math.floor(Math.random() * (max - min + 1)) + min
- • Fast
- • Simple to use
- • Built-in
- • Not cryptographically secure
- • Predictable
- • Not suitable for security
crypto.getRandomValues()
Cryptographically secure random number generator
crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1)
- • Cryptographically secure
- • Unpredictable
- • Suitable for security
- • Slower
- • More complex
- • Not available in all environments
Seeded Random
Deterministic random number generator with seed
seed = (seed * 9301 + 49297) % 233280; return seed / 233280;
- • Reproducible
- • Fast
- • Good for testing
- • Predictable
- • Not secure
- • Limited randomness
Detailed Comparison
Algorithm | Speed | Security | Complexity | Best For |
---|---|---|---|---|
Math.random() Built-in JavaScript random number generator | ⚡⚡⚡ | ❌ | ⭐ | Games, animations, general purpose |
crypto.getRandomValues() Cryptographically secure random number generator | ⚡⚡ | ✅ | ⭐⭐ | Passwords, tokens, security-critical applications |
Seeded Random Deterministic random number generator with seed | ⚡⚡⚡ | ⚠️ | ⭐⭐ | Testing, reproducible results, simulations |
When to Use Which Algorithm?
Performance First
Use Math.random() for games, animations, and non-security applications where speed matters.
Security Critical
Use crypto.getRandomValues() for passwords, tokens, and any security-sensitive operations.
Testing & Debugging
Use seeded random generators for reproducible tests and debugging scenarios.
Best Practices
Use crypto.getRandomValues() for security
When generating passwords, tokens, or any security-critical data, always use the Web Crypto API.
// Good - Secure random number
const secureRandom = crypto.getRandomValues(new Uint32Array(1))[0] / (0xffffffff + 1);
// Bad - Predictable random number
const predictableRandom = Math.random();
Handle edge cases properly
Always validate input parameters and handle edge cases like min > max.
// Good - Handle edge cases
function getRandomInt(min, max) {
if (min > max) [min, max] = [max, min];
return Math.floor(Math.random() * (max - min + 1)) + min;
}
Avoid Math.random() for security
Math.random() is not cryptographically secure and can be predicted.
// Warning - Not secure for passwords
const password = Math.random().toString(36).substring(2, 15);
// Better - Use crypto API
const password = crypto.getRandomValues(new Uint8Array(8))
.reduce((str, byte) => str + byte.toString(16).padStart(2, '0'), '');
Consider performance for large arrays
When generating large arrays of unique numbers, use efficient algorithms.
// Efficient - Fisher-Yates shuffle
function generateUniqueArray(min, max, count) {
const numbers = Array.from({length: max - min + 1}, (_, i) => min + i);
for (let i = numbers.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[numbers[i], numbers[j]] = [numbers[j], numbers[i]];
}
return numbers.slice(0, count);
}
Use appropriate data types
Choose integer or float based on your needs, and specify decimal places for floats.
// Good - Specify decimal places
function getRandomFloat(min, max, decimals = 2) {
const random = Math.random() * (max - min) + min;
return parseFloat(random.toFixed(decimals));
}
Don't use random for IDs
Random numbers are not suitable for generating unique IDs. Use UUID or timestamp-based IDs.
// Bad - Random ID (can collide)
const id = Math.floor(Math.random() * 1000000);
// Good - Use UUID
const id = crypto.randomUUID();
// Good - Timestamp-based ID
const id = Date.now().toString(36) + Math.random().toString(36).substr(2);
Performance Tips
For Small Arrays (< 100 items)
- • Use simple loops with duplicate checking
- • Math.random() is fast enough
- • No need for complex algorithms
For Large Arrays (> 1000 items)
- • Use Fisher-Yates shuffle algorithm
- • Pre-generate the full range
- • Consider using Web Workers for UI responsiveness
Browser Compatibility
Feature | Chrome | Firefox | Safari | Edge |
---|---|---|---|---|
Math.random() | ✅ | ✅ | ✅ | ✅ |
crypto.getRandomValues() | ✅ | ✅ | ✅ | ✅ |
crypto.randomUUID() | ✅ | ✅ | ⚠️ 15+ | ✅ |
Frequently Asked Questions
Related Tools
Random String Generator
Generate secure random strings for passwords, API keys, and more.
- Custom length
- Character sets
- Copy to clipboard
QR Code Generator
Generate QR codes for URLs, text, and contact information.
- Text/URL
- Custom colors
- Download as PNG
Invoice Generator
Create professional invoices online and export as PDF.
- Custom fields
- PDF export
- Branding support
Explore All Tools
Discover our complete collection of JavaScript generators and utilities for developers.
Need More JavaScript Tools?
Explore our collection of free JavaScript generators and utilities
Fast & Reliable
Generate code instantly with our optimized tools
Production Ready
Copy-paste code that works in your projects
Always Free
No registration required, use as much as you need