0
0
JavascriptProgramBeginner · 2 min read

JavaScript Program to Generate Random String

Use Math.random() with a string of characters and pick random characters in a loop like this: function randomString(length) { const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; let result = ''; for (let i = 0; i < length; i++) { result += chars.charAt(Math.floor(Math.random() * chars.length)); } return result; }.
📋

Examples

Input5
OutputaZ3fQ
Input10
Output4bT9xWqP0L
Input0
Output
🧠

How to Think About It

To create a random string, first decide the characters you want to use (like letters and numbers). Then, for the length you want, pick a random character from that set each time and add it to your result. This way, you build a string of random characters step by step.
📐

Algorithm

1
Define a string containing all possible characters to use.
2
Create an empty string to store the result.
3
Repeat for the desired length:
4
Pick a random index within the characters string.
5
Add the character at that index to the result string.
6
Return the final result string.
💻

Code

javascript
function randomString(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  let result = '';
  for (let i = 0; i < length; i++) {
    const randomIndex = Math.floor(Math.random() * chars.length);
    result += chars.charAt(randomIndex);
  }
  return result;
}

console.log(randomString(8));
Output
e.g. "G5kLm2Qz"
🔍

Dry Run

Let's trace generating a random string of length 3 through the code

1

Initialize variables

chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789', result = ''

2

First iteration (i=0)

randomIndex = 12 (example), result = '' + chars.charAt(12) = 'M'

3

Second iteration (i=1)

randomIndex = 35 (example), result = 'M' + chars.charAt(35) = 'Mz'

4

Third iteration (i=2)

randomIndex = 2 (example), result = 'Mz' + chars.charAt(2) = 'MzC'

5

Return result

Return 'MzC'

IterationrandomIndexCharacter AddedResult So Far
112MM
235zMz
32CMzC
💡

Why This Works

Step 1: Character set

We create a string chars with all letters and digits to choose from randomly.

Step 2: Random selection

For each character needed, we use Math.random() to pick a random index in chars.

Step 3: Building the string

We add each randomly chosen character to result until it reaches the desired length.

🔄

Alternative Approaches

Using Array.from and map
javascript
function randomString(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  return Array.from({ length }, () => chars.charAt(Math.floor(Math.random() * chars.length))).join('');
}

console.log(randomString(8));
This method uses array creation and mapping for a concise one-liner inside the function, but may be less clear for beginners.
Using crypto.getRandomValues for better randomness
javascript
function randomString(length) {
  const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
  const array = new Uint32Array(length);
  window.crypto.getRandomValues(array);
  return Array.from(array, num => chars[num % chars.length]).join('');
}

console.log(randomString(8));
This uses the browser's crypto API for stronger randomness, better for security but slightly more complex.

Complexity: O(n) time, O(n) space

Time Complexity

The code runs a loop for the length of the string, so time grows linearly with the requested length.

Space Complexity

The result string grows with the length, so space used is proportional to the output size.

Which Approach is Fastest?

The simple loop and the Array.from methods have similar speed; using crypto is slower but more secure.

ApproachTimeSpaceBest For
Simple loop with Math.randomO(n)O(n)General use, easy to understand
Array.from with mapO(n)O(n)Concise code, functional style
crypto.getRandomValuesO(n)O(n)Security-sensitive applications
💡
Use Math.floor(Math.random() * chars.length) to get a random index safely within the character set.
⚠️
Beginners often forget to use Math.floor, which can cause errors by producing decimal indexes.