How to Generate Random Numbers in JavaScript with Math.random()
In this article, we’ll look at how to generate random numbers in JavaScript with Math.random()
, building a function that you can reuse for a wide range of purposes — such as loading random images, picking a random element from an array, and generating random colors, letters, strings, phrases, and passwords.
Randomness in JavaScript
It’s always useful to be able to add an element of randomness to your programs. You might want to spice up your website by adding some random styles, generate a random phrase, or add an element of chance to a game (they are used extensively in this Numble game, for example).
Unfortunately, it’s actually very hard to create a truly random value (unless you have access to some radioactive material … or a monkey with a keyboard. To get around this, programming languages use deterministic methods to produce pseudo-random numbers. These are numbers that appear to be random, but are actually generated by functions that accept seed values based on events such as the time or position of the mouse pointer.
JavaScript has the random
function, which is a method of the built-in Math
object. The ECMAScript standard doesn’t specify how this function should generate a random number, so it’s left up to the browser vendors to implement. At the time of writing, all the major browsers currently use the xorshift128+ algorithm in the background to generate a pseudo-random number.
To use it, simply enter Math.random()
and it will return a pseudo-random floating point decimal number between 0 (inclusive) and 1 (exclusive):
const x = Math.random();
This can be represented as the following inequality:
0 <= x < 1
But what if you want a random number that’s bigger than 1? Easy: all you need to do is multiply by a scale factor to scale it up — for example, multiplying the result by 10 will produce a value between 0 (inclusive) and 10 (exclusive):
const y = Math.random()*10
The reason for this can be seen if we multiply both sides of the previous inequality by 10:
0 <= y < 10
But the result is still a floating point decimal number. What if we want a random integer? Simple: all we need to do is use the Math.floor
function to round the returned value down to the integer below. The following code will assign a random integer from 0 to 9 inclusive to the variable z
:
const z = Math.floor(Math.random()*10)
Note that, even though we multiply by 10, the value returned only goes up to 9.
We can generalize this method to create a function that will return a random integer between 0 and up to, but not including, the number provided as an argument:
function randomInt(number){
return Math.floor(Math.random()*(number))
}
We can now use this function to return a random digit between 0 and 9:
const randomDigit= randomInt(10)
So now we have a way of creating a random integer. But what about a random integer between two different values, not always starting at zero? All we need to do is use the code above and add on the value we want the range to start from. For example, if we wanted to generate a random integer between 6 and 10 inclusive, we would start by using the code above to generate a random integer between 0 and 4 and then add 6 to the result:
const betweenSixAnd10 = Math.floor(Math.random()*5) + 6
Note that, in order to generate a random integer between 0
and 4
, we actually had to multiply by 5
.
We can generalize this method to create a function that will return a random integer between two values:
function randomIntBetween(min,max){
Math.floor(Math.random()*(max - min + 1)) + min
}
This is simply a generalized form of the code we wrote to get a random number between 6 and 10, but with 6 replaced with the min
parameter and 10 replaced by the max
parameter. To use it, just enter two arguments to represent the lower and upper limits of the random number (inclusive). So to simulate rolling a six-sided dice, we could use the following code to return an integer between 1 and 6:
const dice = randomIntBetween(1,6)
To show how the randomIntBetween
function works, I’ve hooked it up to some HTML in the demo below, so you can change the values of min
and max
and generate a random integer by clicking on the button (which could be used to replicate the different sized dice used in Dungeons & Dragons and similar games).
See the Pen
Random Integer – SitePoint by SitePoint (@SitePoint)
on CodePen.
Now that we have some functions for generating random integers, we can use them to do some interesting stuff.
Load a Random Image
To start with, we’ll use our randomInt
function to load a random photo from the Lorem Picsum website. This site provides a database of placeholder images, each with unique integer ID. This means we can create a link to a random image by inserting a random integer into the URL.
All we need to do is set up the following HTML that will display the image with an ID of 0:
<button id="randomPhoto">Random Photo</button>
<p id="photo"><img src="https://picsum.photos/id/0/200/200"></p>
Then we can hook up the following JavaScript to generate a random integer for the ID and update the HTML to display a new image at random when the button is clicked:
document.getElementById("randomPhoto").addEventListener("click",e => document.getElementById("photo").innerHTML = `<img src="https://picsum.photos/id/${randomInt(100)}/200/200">`)
You can see this on the CodePen demo below.
See the Pen
Random Photo – SitePoint by SitePoint (@SitePoint)
on CodePen.
Generating a Random Color
In HTML and CSS, colors are represented by three integers between 0 and 255, written in hexadecimal (base 16). The first represents red, the second green and the third blue. This means we can use our randomInt
function to create a random color by generating three random numbers between 0 and 255 and converting them to base 16. To convert a number to a different base, you can provide an argument to the toString
method, so the following code will return a random hexadecimal number between 0 and FF (255 in hexadecimal):
randomInt(0,255).toString(16)
<< 2B
We can now write a randomColor
function that will return an HTML color code:
function randomColor(){
return `#${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}${randomInt(1,255).toString(16)}`
}
This returns a template literal that starts with the hash character that all HTML color codes start with and then concatenates three random integers between 0 and 255 in base 16 onto the end.
Calling the randomColor
function will return a random HTML color string:
randomColor()
<< #c2d699
I’ve hooked the function up to an HTML button so that it changes the background color of the document every time the button is clicked in the CodePen demo below.
See the Pen
Random Color – SitePoint by SitePoint (@SitePoint)
on CodePen.
Generating a Random Letter
We’ve already got a function for creating a random integer, but what about random letters? Luckily, there’s a nice way of converting integers into letters using number bases. In base 36, the integers from 10 to 35 are represented by the letters “a” to “z”. You can check this by converting some values to base 36 in the console using the toString
method:
(24).toString(36)
(16).toString(36)
Now that we know this, it should be easy to write a randomLetter
function that uses our randomInt
function to generate a random integer between 10 and 35 and returns its base 36 string representation:
function randomLetter(){
return randomInt(10,35).toString(36)
}
Calling randomLetter
should return a random lowercase letter from “a” to “z”:
randomLetter()
<< "o"
randomLetter()
<< "g"
I’ve hooked the function up to an HTML button so you can see how it works in the CodePen demo below.
See the Pen
Random Letter – SitePoint by SitePoint (@SitePoint)
on CodePen.
Generating a Random String
Now that we can create random letters, we can put them together to create random strings of letters. Let’s write a randomString
function that accepts a single parameter, n
— which represents the number of random letters we want in the string that’s returned. We can create a string of random letters by creating an array or length n
and then using the map
method to change each element to a random letter. We can then use the join
method to convert the array into a string of random letters:
function randomString(numberOfLetters){
return [...Array(numberOfLetters)].map(randomLetter).join``
}
Calling randomString(n)
should return a random string of n
letters:
randomString(5)
<< "xkibb"
randomLetter(3)
<< "bxd"
I’ve hooked the function up to an HTML button so you can see how it works in the CodePen demo below.
See the Pen
Random String – SitePoint by SitePoint (@SitePoint)
on CodePen.
Picking a Random Element from an Array
It’s often useful to be able to pick a random element from an array. This is fairly easy to do using our randomInt
function. We can select an index in the array at random, using the length of the array as the argument and returning the element at that index from the array:
function randomPick(array){
return array[randomInt(array.length)]
}
For example, take the following array that represents a list of fruits:
const fruits = ["🍏",🍌","🍓","🥝","🍋","🍐","🫐","🍉"]
You could pick a random piece of fruit using the following code:
randomPick(fruits)
<< "🍉"
Generating a Random Phrase
Now that we have a function that picks a random element from arrays, we can use it to create random phrases. You often see this technique used as placeholder usernames on websites. To start with, create three arrays, one containing strings of adjectives, one containing colors, and the other nouns, similar to the ones shown below:
const adjectives = ["Quick","Fierce","Ugly","Amazing","Super","Spectacular","Dirty","Funky","Scary"]
const colors = ["Brown","Red","Orange","Black","White","Purple","Pink","Yellow","Green","Blue"]
const nouns = ["Fox","Bear","Monkey","Hammer","Table","Door","Apple","Banana","Chair","Chicken"]
Now that we have these three arrays, creating a random phrase is easy using our randomPick
function. We simply pick a random element from each array and concatenate them, with spaces between them to make a phrase:
function randomPhrase(a,c,n){
return `${randomPick(a)} ${randomPick(c)} ${randomPick(n)}`
}
Calling randomPhrase
should return a slightly funny sounding random phrase — with a color, adjective and noun:
randomPhrase()
<< "Funky Pink Chicken"
I’ve hooked the function up to an HTML button so you can create some whacky phrases by pressing the button in CodePen demo below.
See the Pen
Random Phrase – SitePoint by SitePoint (@SitePoint)
on CodePen.
Generating a Random Password
The last use of random integers that we’ll look at is generating a random password string. The common rules for a password are that it contain at least:
- eight characters
- one numerical character
- one special non-alphanumeric character
An example that fits these rules might be:
secret!1
We already have the functions that can produce each of these elements for us. First of all, we’ll use randomString(6)
to create a random string of six letters. Then we’ll use the randomPick
function to select a special character from an array, and then we’ll use randomInt(9)
to return a random digit. All we need to do then is concatenate them and we’ll have a randomly generated password!
We can put this together into a function that will return a random password string:
function generatePassword(){
return randomString(6) + randomPick(["!","%","?","&","@","£","$","#"]) + randomInt(9)
}
Calling generatePassword
should return a random password that passes the three rules from above:
generatePassword()
<< "ykkefn@8"
I’ve hooked the function up to an HTML button so you can try generating some random passwords by pressing the button in CodePen demo below.
See the Pen
Random Password – SitePoint by SitePoint (@SitePoint)
on CodePen.
One thing to notice is how all the functions we’ve written use the randomInt
function that we wrote at the start. The generatePassword
function that we just wrote, for example, is composed of the randomInt
,randomPick
and randomString
functions … and the randomString
function uses the randomLetter
function! This is a cornerstone of programming: using functions as the building blocks for more complex functions.
Wrapping Up
We’ve discussed how to generate random numbers in JavaScript useful. I hope you found this guide useful. The randomInt
function is certainly a useful function to have in your locker and will help you add some randomness to your projects.
You can see all the examples covered in this article in the following CodePen demo.
See the Pen
Randomness – SitePoint by SitePoint (@SitePoint)
on CodePen.
Related reading:
- How to Convert Numbers to Ordinals in JavaScript
- A Utility Function for Padding Strings and Numbers
- Fun with JavaScript Numbers
FAQs about Math.random()
in JavaScript
Math.random()
is a built-in JavaScript function that generates a pseudo-random floating-point number in the range from 0 (inclusive) to 1 (exclusive).
You can use the formula Math.floor(Math.random() * (max - min + 1)) + min
to generate a random integer between min
(inclusive) and max
(inclusive).
No, it’s not truly random. JavaScript uses a pseudo-random number generator algorithm. The sequence of numbers generated is deterministic and depends on the initial seed value.
No, there is no built-in way to set a seed for Math.random()
in standard JavaScript. If you need more control over randomness, consider using external libraries like the seedrandom
library.
Yes, you can scale the result to obtain more decimal places. For example, to get a random number with two decimal places between 0 and 1, you can use Math.random().toFixed(2)
.