This guide will show you how to quickly and easily generate random numbers and strings in the JavaScript programming language.
Generating random values is a common and important task when programming almost any kind of application of moderate complexity.
Random strings and numbers are used to generate unique identifiers (e.g., for the short URLs in URL shortening services), for identifying unique records in a database, and (most importantly) are frequently used to determine the behavior of gameplay elements in video games (for example, simulating a coin flip, or generating random terrain).
Generating Random Numbers in JavaScript using Math.random()
The JavaScript Math.random() function returns a random floating-point number between 0 and 1. It’s super easy to use:
var myRandomNumber = Math.random(); // A value between 0 and 1
But what if you want an integer? Combine it with the Math.floor() function, which rounds a number down to the nearest integer, and multiply the random number by the maximum number you’d like to receive:
var myRandomInteger = Math.floor(Math.random() * 15);
The above example will assign a random integer from 0-15 to the myRandomInteger variable.
This concept can be expanded to get a random integer value between any two values:
function getRandomInteger(min, max) { min = Math.ceil(min); max = Math.floor(max); return Math.floor(Math.random() * (max - min + 1) + min); //The maximum is inclusive and the minimum is inclusive }
Which can be used like so:
var myRandomInteger = getRandomInteger(2, 18);
Which would return a random integer between 2 and 18, inclusive.
Want to get a floating-point number between min and max? Remove the final Math.floor() to stop the result from being rounded to the nearest integer.
Generating Random Strings in JavaScript
There’s no built-in JavaScript way to generate a random string, so here’s a neat DIY solution:
function randomString(minChars, maxChars) { Math.random().toString(36).substr(minChars, maxChars); }
So what’s going on here?
- Math.random() is called
- The result is converted to a string using toString() with a radix of 36
- Keeping it simple, that radix converts the random value represented by numerical digits to one with a high radix where the random number is represented by alphabetical letters
- The result of all of that is then trimmed using substr() to cut the string to the necessary length
- There is an astronomically small chance an empty string will be returned if Math.random() returns 0
- As we’re a teachin’ site, I’ve used this example as it’s easy to explain why it’s doing what it’s doing
- Check out this answer on StackOverflow for a discussion and solution to this problem
This function can be used like so:
var myRandomString = randomString(2,6);
The above example will generate a random string between 2 and 6 characters in length.
Security Warning!
All random values generated using the above code are considered pseudo-random, random enough for general use but not random enough for bulletproof security when hashing passwords or generating secure ciphers.
If you want to secure your application using random data – you MUST use an appropriate cryptographic library.
Even better – just don’t. Instead, use a pre-built authentication or cryptography library. Rolling your own authentication and encryption services using tutorials you’ve found online is a good way to have your data compromised. Just integrate a solution made by the pros – you’ll save time and worry less.