Generating random numbers in JavaScript with Math.random()

In this article, we will see how to generate random numbers in JavaScript with Math.random()by creating a function that you can reuse for various purposes, such as loading random images, selecting a random element from an array, and generating colors, letters, strings, phrases, and passwords random.

Random 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 random styles, generate a random phrase, or add an element of luck to a game (they’re heavily used in this Numble game, for example).

Unfortunately, it’s actually very difficult to create a truly random value (unless you have access to radioactive materials…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 be random, but are actually generated by functions that accept starting values based on events such as time or mouse pointer position.

JavaScript has the random function, which is a method of the built-in function Math object. The ECMAScript standard does not specify how this function should generate a random number, so it is up to browser vendors to implement it. As of this writing, all major browsers currently use the xorshift128+ algorithm in the background to generate a pseudo-random number.

To use it, just 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 by the following inequality:

0 <= x < 1

But what if you want a random number greater than 1? Easy: all you have to do is multiply by a scale factor to scale it — 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 is visible if we multiply both sides of the previous inequality by 10:

0 <= y < 10

But the result is still a decimal floating point number. What if we wanted a random integer? Simple: just use the Math.floor function to round the returned value down to an integer. 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 if we multiply by 10, the returned value 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 understoodthe number given as argument:

function randomInt(number){
  return Math.floor(Math.random()*(number))
}  

We can now use this function to return a random number between 0 and 9:

const randomDigit= randomInt(10)

So now we have a way to create a random integer. But what about a random integer between two different values, not always starting at zero? All we have to do is use the code above and to add on the value from which we want the range to start. 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, then add 6 to the result:

const betweenSixAnd10 = Math.floor(Math.random()*5) + 6

Note that, to generate a random integer between 0 and 4we 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 just a generalized form of the code we wrote to get a random number between 6 and 10, but with 6 replaced by the min parameter and 10 replaced by the max setting. To use it, just enter two arguments to represent the lower and upper bounds of the random number (inclusive). So, to simulate rolling a six-sided die, 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 hooked it up to HTML in the demo below, so you can change the values ​​of min and max and generate a random integer by clicking 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 things.

Load a random image

To start, we will use our randomInt function to load a random photo from the Lorem Picsum website. This site provides a database of placeholder images, each with a unique integer ID. This means we can link to a random image by inserting a random integer into the URL.

All we have to do is configure the following HTML which will display the image with an ID of 0:

<button id="randomPhoto">Random Photobutton>
<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 random image 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 it on the CodePen demo below.

See the pen
Random Photo – SitePoint by SitePoint (@SitePoint)
on CodePen.

Generate 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 that we can use our randomInt 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 supply an argument to the toString so the following code will return a random hex number between 0 and FF (255 in hex):

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 literal pattern that starts with the hash character that all HTML color codes begin with, then concatenates three random integers between 0 and 255 in base 16 to the end.

Calling him randomColor will return a random HTML color string:

randomColor()
<< #c2d699

I’ve hooked up the function to an HTML button so that it changes the background color of the document each time the button is clicked in the CodePen demo below.

See the pen
Random Color – SitePoint by SitePoint (@SitePoint)
on CodePen.

Generate a random letter

We already have a function to create a random integer, but what about random letters? Fortunately, there is a good way to convert whole numbers to 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 that, it should be easy to write a randomLetter function that uses our randomInt to generate a random integer between 10 and 35 and return its representation as a base-36 string:

function randomLetter(){
 return randomInt(10,35).toString(36)
}

Call 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 letter strings. Let’s write a randomString function that accepts a single parameter, n — which represents the number of random letters we want in the returned string. We can create a string of random letters by creating an array or a length n then using the map method to change each item to a random letter. You can then use the join method to convert the array to a string of random letters:

function randomString(numberOfLetters){
  return [...Array(numberOfLetters)].map(randomLetter).join``
}

Call 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.

Choose a random element from an array

It is often useful to be able to choose a random element from an array. This is quite easy to do using our randomInt function. We can select an index in the array at random, using the length of the array as an argument and returning the element at that index from the array:

function randomPick(array){
 return array[randomInt(array.length)]
}

Take for example the following table which represents a list of fruits:

const fruits = ["🍏",🍌","🍓","🥝","🍋","🍐","🫐","🍉"]

You can choose a fruit at random using the following code:

randomPick(fruits)
<< "🍉"

Generate a random phrase

Now that we have a function that selects a random element from arrays, we can use it to create random sentences. You often see this technique used as placeholder usernames on websites. To get started, 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, it’s easy to create a random phrase using our randomPick function. We simply choose a random element from each array and concatenate them, with spaces between them to form a sentence:

function randomPhrase(a,c,n){
  return `${randomPick(a)} ${randomPick(c)} ${randomPick(n)}`
}

Call randomPhrase should return a slightly funny-sounding random phrase — with a color, an adjective, and a noun:

randomPhrase()
<< "Funky Pink Chicken"

I’ve hooked up the function to an HTML button so you can create wacky phrases by pressing the button in the CodePen demo below.

See the pen
Random phrase – SitePoint by SitePoint (@SitePoint)
on CodePen.

Generate a random password

The last use of random integers that we will look at is generating a random password string. The common rules for a password are that it contains at least:

  • eight characters
  • a numeric character
  • a non-alphanumeric special character

An example that fits these rules could be:

secret!1

We already have the functions that can produce each of these elements for us. First, we will use randomString(6) to create a random string of six letters. Then we will use the randomPick function to select a special character from an array, then we will use randomInt(9) to return a random number. All we have to do is concatenate them and we’ll have a randomly generated password!

We can put this together in a function that will return a random password string:

function generatePassword(){
  return randomString(6) + randomPick(["!","%","?","&","@","£","$","#"]) + randomInt(9)
}

Call generatePassword should return a random password that follows the three rules above:

generatePassword()
<< "[email protected]"

I’ve hooked up the function to an HTML button so you can try generating random passwords by pressing the button in the CodePen demo below.

See the pen
Random Password – SitePoint by SitePoint (@SitePoint)
on CodePen.

One thing to notice is that all the functions we wrote use the randomInt function we wrote at the beginning. The generatePassword function we just wrote, for example, is composed of randomInt,randomPick and randomString functions … and the randomString the function uses the randomLetter function! It’s a cornerstone of programming: using functions as building blocks for more complex functions.

Wrap

We discussed how to generate random numbers in useful JavaScript. I hope you found this guide useful. The randomInt The feature is definitely a useful feature to have in your locker and will help you add a bit of randomness to your projects.

You can see all of the examples covered in this article in the following CodePen demo.

See the pen
Random – SitePoint by SitePoint (@SitePoint)
on CodePen.

Related reading:

Comments are closed.