To create a random number in JavaScript, the core tool is Math.random(), which returns a floating-point number between 0 (inclusive) and 1 (exclusive). From there you can scale and shift it to get integers or decimals in any range you need. This guide covers the essential patterns, common pitfalls, and practical examples.
What You’ll Need
- A web browser with developer tools (press F12 or right-click > Inspect) or any environment that runs JavaScript, like Node.js.
- Basic familiarity with JavaScript syntax (variables, functions, console).
Step-by-Step
- Generate a basic random decimal. Call
Math.random()to get a number between 0 and just under 1. For example, open your browser console and typeconsole.log(Math.random()). You’ll see something like0.732. This is your foundation. - Scale to a range. Multiply the result by the size of the range you want. To get a number between 0 and 10, use
Math.random() * 10. This gives a float like7.123. - Shift the range. Add a starting value to move the range. For a number between 5 and 15, first calculate the range size (15 – 5 = 10), then do
Math.random() * 10 + 5. This yields values from 5 up to (but not including) 15. - Get a random integer. Use
Math.floor()to round down to the nearest whole number. For a random integer between 0 and 9, useMath.floor(Math.random() * 10). The* 10produces 0 to 9.999…, andMath.floor()turns that into 0–9. - Create a reusable function. Write a function that takes a minimum and maximum (inclusive) and returns a random integer. Here’s a standard implementation:
function getRandomInt(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1)) + min; }This works because
max - min + 1gives the number of possible values, and addingminshifts the result. For example,getRandomInt(1, 6)simulates a die roll. - Handle non-integer ranges. If you need a random float between two numbers, use
Math.random() * (max - min) + min. For a random decimal between 1.5 and 5.5, doMath.random() * 4 + 1.5. - Use a cryptographically secure generator when needed. For security-sensitive applications (like password generation or gambling),
Math.random()is not suitable because it’s not cryptographically secure. Instead, use the Web Crypto API:crypto.getRandomValues(). Here’s an example for a random integer between 0 and 255:const arr = new Uint8Array(1); crypto.getRandomValues(arr); const randomInt = arr[0]; // 0 to 255In Node.js, you can use
crypto.randomInt()for integers.
Common Mistakes
- Forgetting that
Math.random()never returns 1. If you useMath.round()instead ofMath.floor(), the maximum value becomes twice as likely as others. For example,Math.round(Math.random() * 10)gives 0–10, but 0 and 10 each have half the probability of the numbers 1–9. UseMath.floor()for uniform distribution. - Off-by-one errors. If you want numbers from 1 to 10 inclusive, using
Math.floor(Math.random() * 10) + 1is correct. But if you mistakenly use* 11, you’ll get 1–11, which is wrong. - Using
Math.random()for security. It’s predictable and can be exploited. Never use it for passwords, tokens, or any security-related randomness. - Assuming the range is inclusive on both ends. By default,
Math.random()gives an exclusive upper bound. If you need the maximum to be included, you must add 1 to the multiplier and then floor.
Tips
- Use a helper function for clarity. Instead of repeating the formula, define a function like
randomInt(min, max)and reuse it. This reduces errors. - Remember that
Math.random()is not seedable. You cannot set a seed for reproducible results. For simulations that need reproducibility, consider a custom pseudo-random number generator (PRNG) like a linear congruential generator, but for most web tasksMath.random()is fine. - For arrays, use
Math.random()to pick a random element:arr[Math.floor(Math.random() * arr.length)]. - To shuffle an array, use the Fisher-Yates algorithm with
Math.random(); it gives a uniform shuffle. - When generating many random numbers, performance is rarely an issue with
Math.random(), but if you need millions, consider using a generator likemulberry32for speed.
Troubleshooting
- My random numbers are always the same. That’s not possible with
Math.random()in a normal environment; it’s seeded by the system. If you’re using a custom PRNG with a fixed seed, that’s expected. If you’re seeing the same value repeatedly in a loop, check that you’re callingMath.random()inside the loop, not once before it. - I get a negative number. This happens if you subtract instead of add the minimum. For example,
Math.random() * 10 - 5gives -5 to 5. If you want 5 to 15, use+ 5. - I get a decimal when I wanted an integer. You forgot to use
Math.floor(). Wrap the expression withMath.floor()or useMath.trunc()for positive numbers. - My function returns a value outside the range. Double-check your min/max arithmetic. For inclusive integers, the formula is
Math.floor(Math.random() * (max - min + 1)) + min. If you usemax - minwithout the +1, the max is never returned. - In Node.js,
crypto.getRandomValuesis not defined. That’s a browser API. Usecrypto.randomInt(min, max)from the built-incryptomodule instead.
Frequently Asked Questions
- Can I generate a random number between 1 and 100? Yes. Use
Math.floor(Math.random() * 100) + 1for an integer from 1 to 100 inclusive. - How do I generate a random decimal between two numbers? Use
Math.random() * (max - min) + min. For example,Math.random() * 9 + 1gives a number from 1 to just under 10. - Is
Math.random()truly random? No, it’s a pseudo-random number generator. It’s deterministic but appears random. For most non-security purposes, it’s sufficient. - How can I make the random number unpredictable for security? Use the Web Crypto API:
crypto.getRandomValues()in browsers, orcrypto.randomBytes()in Node.js. These are cryptographically secure. - Can I set a seed to get the same sequence every time?
Math.random()doesn’t support seeding. You can implement your own seeded PRNG, like a simple LCG, if you need reproducibility. - Why do I sometimes get 0 but never get the maximum? That’s because
Math.random()returns values from 0 up to but not including 1. When you multiply by the range size and floor, the maximum is never reached unless you add 1 to the multiplier.
Related
- Refresh Shortcut Windows: How to Do It
- Data Entry for Registration of Documents: How It Works
- Ctrl+Z Shortcut: What It Does and How to Use It
Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.
More in How-to basics
- Google Sheets Current Timestamp: Insert or Update ItTo show the current date and time in Google Sheets, enter =NOW() in a cell. It updates when…
- How to Mail Merge in Word 2010: A Step-by-Step GuideTo mail merge in Word 2010, open the Mailings tab, choose Start Mail Merge or Step-by-Step Mail Merge…
- Excel Equation to Merge Cells? The Real AnswerThere is no Excel equation that merges cells: formulas calculate values, but they cannot change the worksheet layout.…
- Excel Remove Duplicates: Keep the Last Matching RecordExcel’s Remove Duplicates command keeps the first matching row it encounters; it has no built-in option to keep…
- F-Strings in JavaScript: Use Template Literals InsteadJavaScript does not have Python-style f-strings. Its closest equivalent is a template literal: write the string between backticks…
- How to Insert a Line Break in Microsoft Word: Quick StepsTo insert a line break in Microsoft Word without starting a new paragraph, place the cursor where the…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.