Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Random name generator function in JavaScript
We are required to write a JavaScript function that takes in a number n and returns a random string of length n containing no other than the 26 English lowercase alphabets.
Example
Let us write the code for this function:
const num = 8;
const randomNameGenerator = num => {
let res = '';
for(let i = 0; i < num; i++){
const random = Math.floor(Math.random() * 26);
res += String.fromCharCode(97 + random);
};
return res;
};
console.log(randomNameGenerator(num));
Output
Following is the output in the console:
kdcwping
Note: This is one of many possible outputs. Console output is expected to differ every time.
How It Works
The function uses Math.random() to generate random numbers between 0-25, then converts them to ASCII characters:
// Breaking down the logic
console.log("ASCII code for 'a':", 'a'.charCodeAt(0)); // 97
console.log("Random number 0-25:", Math.floor(Math.random() * 26));
console.log("Character from code 97+5:", String.fromCharCode(97 + 5)); // 'f'
ASCII code for 'a': 97 Random number 0-25: 12 Character from code 97+5: f
Alternative Approach Using Array
You can also use a predefined alphabet array for cleaner code:
const randomNameGeneratorArray = num => {
const alphabet = 'abcdefghijklmnopqrstuvwxyz';
let result = '';
for(let i = 0; i < num; i++){
const randomIndex = Math.floor(Math.random() * alphabet.length);
result += alphabet[randomIndex];
}
return result;
};
console.log(randomNameGeneratorArray(10));
console.log(randomNameGeneratorArray(5));
mxqweropls jhkdf
Conclusion
Both approaches generate random lowercase strings effectively. The ASCII method is more memory-efficient, while the array approach is more readable and easier to understand.
Advertisements
