Advertisement
  1. Code
  2. JavaScript

Generate Random Numbers and Strings in JavaScript

Scroll to top
Read Time: 9 min

The ability to generate random numbers or alphanumeric strings can come in handy in many situations. You could use it to spawn enemies or food at different locations in a game. You could also use it to suggest random passwords to users or create filenames to save files.

I wrote a tutorial on how to generate random alphanumeric strings in PHP. I began that post by saying that almost no event is truly random, and the same thing applies to random number or string generation.

In this tutorial, I will show you how to generate pseudo-random alphanumeric strings in JavaScript.

Generating Random Numbers in JavaScript

Let's begin by generating random numbers. The first method that comes to mind is Math.random(), which gives back a floating-point pseudo-random number. The random number will always be greater than or equal to 0 and less than 1.

The distribution of the numbers returned in that range is almost uniform, so the method can work well for generating random numbers without noticeable bias in everyday usage. Here is the output of ten calls to the Math.random() method:

1
for(let i = 0; i < 10; i++) {
2
  console.log(Math.random());
3
}
4
5
/* Outputs:

6
0.9981169188071801

7
0.7073616929117277

8
0.05826679080842556

9
0.30779242012809105

10
0.37282814053539926

11
0.8991639574910759

12
0.5851162879630685

13
0.40572834956467063

14
0.5286480734412005

15
0.07898699710613699

16
*/

Generating Random Integers Within a Range

As you saw in the previous section, Math.random() will give us random numbers in the range 0 (inclusive) to 1 (exclusive). Let's say we want random integers in the range 0 (inclusive) to 100 (exclusive). All we need to do here is multiply the original range by 100.

Taking the first output value from the above code snippet as an example, 0.9981169188071801 will become 99.81169188071801 when multiplied by 100. Now, we can use the Math.floor() method, which will round down and return the largest integer less than or equal to 99.81169188071801. In other words, it will give us 99.

The following code snippet will iterate through a loop 10 times to show all these steps applied to different numbers.

1
const max_limit = 100;
2
3
for(let i = 0; i < 10; i++) {
4
  let random_float = Math.random();
5
  let scaled_float = random_float * max_limit;
6
  let random_integer = Math.floor(scaled_float);
7
  
8
  let rf_str = random_float.toString().padEnd(20, ' ');
9
  let sf_str = scaled_float.toString().padEnd(20, ' ');
10
  let ri_str = random_integer.toString().padStart(2, ' ');
11
  
12
  console.log(`Random Float: ${rf_str} Scaled Float: ${sf_str} Random Integer: ${ri_str}`);
13
}
14
15
/* Outputs:

16
Random Float: 0.7976037763162469   Scaled Float: 79.76037763162469    Random Integer: 79

17
Random Float: 0.3794078358214559   Scaled Float: 37.94078358214558    Random Integer: 37

18
Random Float: 0.5749118617425708   Scaled Float: 57.49118617425708    Random Integer: 57

19
Random Float: 0.7110572178100005   Scaled Float: 71.10572178100006    Random Integer: 71

20
Random Float: 0.9157559644743132   Scaled Float: 91.57559644743132    Random Integer: 91

21
Random Float: 0.8773095295734263   Scaled Float: 87.73095295734264    Random Integer: 87

22
Random Float: 0.7714603913623834   Scaled Float: 77.14603913623834    Random Integer: 77

23
Random Float: 0.6431998616346499   Scaled Float: 64.31998616346499    Random Integer: 64

24
Random Float: 0.7909155691442253   Scaled Float: 79.09155691442254    Random Integer: 79

25
Random Float: 0.1219575935563590   Scaled Float: 12.19575935563590    Random Integer: 12

26
*/

Now that you understand the logic behind the multiplication and flooring, we can write a function that generates a random integer within the maximum limit.

1
function max_random_number(max) {
2
  return Math.floor(Math.random() * max);
3
}
4
5
for(let i = 0; i < 10; i++) {
6
  console.log(max_random_number(100));
7
}
8
9
/* Outputs:

10
35

11
23

12
92

13
94

14
42

15
9

16
12

17
56

18
40

19
21

20
*/

What if you want to generate random numbers that are above a specified minimum value but below the maximum value?

In this case, you can add the minimum value beforehand to make sure that the generated number is at least equal to the minimum value. After that, you can simply generate a random number and then scale it by max - min before adding it to the minimum possible value.

1
function min_max_random_number(min, max) {
2
  return min + Math.floor(Math.random() * (max - min));
3
}
4
5
for(let i = 0; i < 10; i++) {
6
  console.log(min_max_random_number(50, 100));
7
}
8
9
/* Outputs:

10
96

11
81

12
95

13
56

14
73

15
72

16
71

17
90

18
51

19
53

20
*/

Generate Cryptographically Secure Random Numbers

The Math.random() method is not suitable for generating cryptographically secure random numbers, but the Crypto.getRandomValues() method can help us here. This method fills the passed array with cryptographically secure pseudo-random numbers. Keep in mind that the algorithm used to generate these random numbers may vary across user agents.

As I mentioned earlier, you need to pass an integer-based TypedArray to the method for it to fill it with random values. The original contents of the array will be replaced. The following code will fill our ten-element array with random integers.

1
let random_values = new Uint8Array(10);
2
console.log(random_values);
3
// Outputs: Uint8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

4
5
crypto.getRandomValues(random_values);
6
console.log(random_values);
7
// Outputs: Uint8Array(10) [ 207, 209, 1, 145, 70, 111, 21, 141, 54, 200 ]

The Unit8Array() constructor gave us an array of ten 8-bit unsigned integers. The array values are all initialized to zero.

Once we pass this array to our getRandomValues() method, the value of random numbers will stay between 0 and 255. You can use other typed arrays to generate random numbers in different ranges. For example, using an Int8Array() constructor will give us an array with integer values between -128 and 127. Similarly, using a Uint16Array() will give us an array with integer values up to 65,535.

1
let random_values = new Int8Array(10);
2
console.log(random_values);
3
// Outputs: Int8Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

4
5
crypto.getRandomValues(random_values);
6
console.log(random_values);
7
// Outputs: Int8Array(10) [ -82, -106, 87, 64, 42, -36, -53, 27, -38, 4 ]

8
9
10
let random_values = new Uint16Array(10);
11
console.log(random_values);
12
// Outputs: Uint16Array(10) [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ]

13
14
crypto.getRandomValues(random_values);
15
console.log(random_values);
16
// Outputs: Uint16Array(10) [ 47615, 60195, 53177, 15169, 215, 4928, 12200, 6307, 30320, 20271 ]

Generate a Random Alphanumeric String in JavaScript

We will now use the knowledge gained in the previous section to generate random alphanumeric strings in JavaScript.

The concept is pretty simple. We will begin with a string that contains all our desired characters. In this case, the string will consist of lowercase letters, uppercase letters, and numbers from 0 to 9. You probably already know that we can access the character at a particular position in a string by passing it an index value.

All we need to do to generate random alphanumeric strings is generate random numbers and then access the character at that random index to append it to our random string. The following code snippet wraps it all up in a nice little function:

1
const char_set = 'abcdefghijlkmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
2
3
function max_random_number(max) {
4
  return Math.floor(Math.random() * max);
5
}
6
7
function get_random_string(length) {
8
  let random_string = '';
9
10
  for(let i = 0; i < length; i++) {
11
    random_string += char_set[max_random_number(char_set.length - 1)];
12
  }
13
  
14
  return random_string;
15
}
16
17
console.log(get_random_string(20));
18
// Outputs: lgtuRJZolu7AXj4HMoiM

19
20
console.log(get_random_string(40));
21
// outputs: scOoal3VXgeAjaHIieolhi2TyWFpAn5bBPPiX6UG

Using toString() to Generate Random Alphanumeric Strings

Another approach that we can take to generate random alphanumeric strings is to use the toString() method on our randomly generated numbers. The toString() method returns a string that represents our specified numerical value. This method accepts an optional radix parameter that specifies the base in which you want to represent the number. A value of 2 will return a binary string, and a value of 16 will return a hexadecimal string. The default value of this parameter is 10. The maximum value can be 36 as it covers all 26 letters and 10 digits.

Here is the output of a few calls to this method for different radix values:

1
let number = 3498650143868;
2
3
console.log(number.toString(2));
4
// Outputs: 110010111010010111110011001000110001111100

5
6
console.log(number.toString(10));
7
// Outputs: 3498650143868

8
9
console.log(number.toString(16));
10
// Outputs: 32e97cc8c7c

11
12
console.log(number.toString(36));
13
// Outputs: 18n99yoak

You might have noticed that the length of the output string keeps decreasing as we increase the radix. In the following code snippet, we will use our max_random_number() function from the previous section to get a random number. We will then convert this random number to an alphanumeric string by using the toString() method.

1
function max_random_number(max) {
2
  return Math.floor(Math.random() * max);
3
}
4
5
for(let i = 0; i < 10; i++) {
6
  console.log(max_random_number(Number.MAX_SAFE_INTEGER).toString(36));
7
}
8
/* Outputs:

9
1tr84s6c2sl

10
1yj4varyoj7

11
1zdg9nn0z6r

12
lubrjj1zih

13
13tt2n5vw9t

14
1mv6sctjgf

15
yx3fhnznhf

16
1wj4mdcrqb9

17
26sir75af2r

18
qdv9xv800t

19
*/

What if you want even larger alphanumeric strings and want them to have a fixed length like 40 characters or 100 characters? In that case, we can create a loop that keeps appending our generated strings until we reach the desired length.

1
function max_random_number(max) {
2
  return Math.floor(Math.random() * max);
3
}
4
5
function get_random_string(length) {
6
  let random_string = '';
7
  while(random_string.length < length) {
8
   random_string += max_random_number(Number.MAX_SAFE_INTEGER).toString(36);
9
  }
10
  return random_string.substring(0, length);
11
}
12
13
console.log(get_random_string(40));
14
// Outputs: bn0nfhcsjm18ylzqrm6bo1iktka2aq7qbbl5ybki

15
16
console.log(get_random_string(100));
17
// Outputs: rdosjhthsevmk91mj9zvqexz2z0v3pe2beasbzoworanzjg3bfpf975rzfy2fmo6pmj4p69u0x80ce92jh2vljx90g6r0lzd8vb0

Final Thoughts

In this tutorial, we learned how to generate random numbers and alphanumeric strings in JavaScript. Generating random integers is easy in JavaScript with the help of the Math.random() method. All we had to do was scale the output so that it matched our desired range. You can also consider using the getRandomValues() method if you want your random numbers to be cryptographically secure.

Once we know how to generate random numbers, creating random alphanumeric strings is easy. All we need to do is figure out how to convert our numbers to characters. We used two approaches here. The first one involved accessing the characters at a random numerical index in a predefined string. This technique is useful if you want to be specific about the characters that should be included in the random alphanumeric strings. The other approach involved using the toString() method to convert our decimal numbers to a different base. This involves fewer calls to our max_random_number() function.

There are certainly many more techniques that you can use to generate random alphanumeric strings. It all depends on your needs and how creative you want to be with your approach.

Advertisement
Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Advertisement
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.