How can I generate random number between number A and number B in javascript ?
Math.floor(a + Math.random() * (b - a))is there any other efficient way to generate random numbers?
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
For stronger randomness (useful for security tokens, password generators or games), JavaScript provides a built-in Crypto API.
This API produces random values that are much harder to predict than Math.random().
function cryptoRandom(a, b) {
const rand = crypto.getRandomValues(new Uint32Array(1))[0] / 2 ** 32;
return Math.floor(rand * (b - a + 1)) + a;
}Example:
console.log(cryptoRandom(1000, 9999)); // Output: Secure random integer between 1000 and 9999 How it works:
crypto.getRandomValues()uses the operating system’s secure random number generator.- Dividing by
2 ** 32normalizes the number to a range between 0 and 1. - The rest of the math is similar to the standard version, it scales and shifts the value between
aandb.
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
Using window.crypto.randomUUID() (for unique random identifiers)
While not for numbers directly, it can be used to generate unique random strings and you can extract numeric parts.
Example:
const id = crypto.randomUUID();
console.log(id); // "3f4a0b8b-23f1-4e99-bcf3-8f9a7b8413cd" You can convert a portion of it to a number if needed:
const num = parseInt(id.replace(/-/g, '').slice(0, 8), 16);
Use this for: generating random unique IDs, order numbers or tracking codes.
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
use Nanoid for Fast and secure random number generation
npm install nanoid
import { nanoid } from 'nanoid';
console.log(nanoid()); // e.g. "V1StGXR8_Z5jdHi6B-myT" (21 chars)
console.log(nanoid(10)); // e.g. "kE93sdPqW1" (10 chars) Use for: unique IDs, file names, sessions, database keys. It is Fast, secure and URL-safe random ID generator.
For random number generation can use below code
import { nanoid } from 'nanoid';
// Generate a random numeric ID (only digits)
function nanoidNumber(length = 6) {
const digits = '0123456789';
return Array.from({ length }, () => digits[Math.floor(Math.random() * 10)]).join('');
}
// Example usage
console.log(nanoidNumber()); // e.g. "583920"
console.log(nanoidNumber(10)); // e.g. "3847569201"
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
Using Date.now() and Random Modifiers
Not truly random, but sometimes used for pseudo-random values when seeding or generating IDs.
Example:
function timeBasedRandom(a, b) {
const rand = (Date.now() % 1000) / 1000;
return Math.floor(rand * (b - a + 1)) + a;
}
Use this for: temporary identifiers or quick unique values (not secure).
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
Custom Random Generator (Using Seeds)
If you want reproducible randomness (same output every time using the same seed), use a seeded random function.
Example:
function seededRandom(seed, a, b) {
const x = Math.sin(seed++) * 10000;
const rand = x - Math.floor(x);
return Math.floor(rand * (b - a + 1)) + a;
}
Use this for: simulations, games or tests where you need predictable random sequences.
Please pay attention to update your answer.
Update Your Answer care fully. After saving you can not recover your old answer
Using External Libraries (More Options & Control)
Several libraries provide advanced randomization features. you can use any Library to generate a high quality random value.
Libraries that you can use:
- Lodash – Simple and reliable random number generator for integers and floats.
- Chance.js – Powerful library for generating random numbers, strings and fake data.
- Random.js – Advanced random number generator with seeding and distribution support.
- Seedrandom – Deterministic random generator that allows reproducible randomness via seeds.
- Crypto-random-string – Generates cryptographically secure random strings.
- @faker-js/faker – Creates realistic fake data (names, emails, numbers etc.) for testing.
- Nanoid – Tiny, secure and fast library for generating unique random IDs.
- Randomatic – Generates random strings, numbers or patterns with custom masks.
- Random-seed – Lightweight library for creating multiple seeded random number generators.
- UUID / crypto.randomUUID() – Built-in secure random UUID generator for unique identifiers.
Example with Lodash:
// Install Lodash: npm install lodash
import { random } from "lodash";
console.log(random(5, 15)); // random integer between 5 and 15
console.log(random(5, 15, true)); // random float between 5 and 15 Use this for: convenience and better readability in larger projects.
