Random name generator function in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

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() * 27);
      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/

raja
Published on 18-Sep-2020 08:53:10
Advertisements