Generating Random Numbers and Strings

Quick start with Math.random

Cristian Salcescu
Frontend Essentials

--

Photo by the author

How would you generate a random number? What about a random string?

You may already know the built-in Math.random function. It generates a random number between 0 and 1, not including the 1 number.

Generating a Random Number

Below is an example of using this utility.

const no = Math.random();
console.log(no);
//0.9045660913804647

As you can notice the given result is a decimal number.

How can we generate an integer number in a specific interval?

To get a number between 0 and 100, we can simply multiply the result by 100.

const no = Math.random() * 100;
console.log(no);
//95.76815468403498

To get an integer we can just round that number to the nearest integer using Match.ceil or Math.floor.

The Math.ceil function rounds the number up to the next largest integer.

The Math.floor function returns the largest integer less than or equal to a given number.

const no = Math.floor(Math.random() * 100);
console.log(no);
//21

Generating a Random Integer Number in a Specified Interval

Now let’s write a function generating a random number between min and max, not including max.

To generate a random number between 0 and 5, we take the initial decimal number which belongs to the interval [0,1) and multiply it by 5 to get a decimal number between [0, 5).

To generate a random number between 1 and 6, we take the initial decimal number which belongs to the interval [0,1) and multiply it by 5 (6 — 1) to get a decimal number between [0, 5). By adding 1 to this result, we get a number between [1, 6).

To generate a random number between min and max, we take the initial decimal number which belongs to the interval [0,1) and multiply it by (max — min)to get a decimal number between [0, max — min). By adding min to this result, we get a number between [min, max).

function randomNumber(min, max){
const result = Math.random() * (max - min) + min;
return Math.floor(result);
}

Generating a Random String of Specific Length

Next, let’s try to generate a string containing both numbers and letters. Consider the next random number.

const random = Math.random();
console.log(random);
//0.7136486017035995

Here is how it looks in base 16.

const random = 0.7136486017035995;
console.log(random.toString(16));
//"0.b6b1acbd2730e"

Here is the same number in base 32.

const random = 0.7136486017035995;
console.log(random.toString(32));
//"0.mqoqpf9763g"

The toString method converts a number to a string. It takes an optional base argument. In that case, it converts first the number to the given base.

Notice that we need to remove the first two characters from the generated string. It can be done using the substr method.

const random = Math.random().toString(32).substr(2, 10);
console.log(random);
//r0hjveqmdv

Here is a function generating a random string anywhere between 1 and 10 characters:

const randomString = (length = 10) => {
return Math
.random()
.toString(32)
.substr(2, length);
};

Generating Large Random Strings

The previous function is not able to generate strings with more than 12 characters.

Next, we will write a function generating strings of any size containing the following random characters A-Z, a-z, and 0-9.

Here is a string constant containing all these characters.

const chars = 
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';

The getRandomIndex generates a random index up to the maximum number of elements.

function getRandomIndex(max){
const number = Math.random() * max;
return Math.floor(number);
}

The toRandomChar function returns a random character.

function toRandomChar(){
const index = getRandomIndex(chars.length);
return chars.charAt(index);
}

Now using the previous toRandomChar function we can generate a random string of any size.

function randomString(length = 16) {
const arr = Array(length).fill('');
return arr
.map(toRandomChar)
.join('')
};

Let’s explain what is going on.
An array with the given length is generated. All elements of this array are empty strings. The map array method is then used to create a new array of the same size containing random characters. Then the computed array is transformed into a string using the join method. It concatenates all the string elements into a new string.

Below are two examples of using this function utility.

randomString(16);
//pTNQ8yQ1rLAL5nb8

randomString(32);
//92mlTMW2WyyBncBHy9qWbMpxL4B6KZW6

That’s all. Thanks for reading.

--

--