Generating random string with a specific length in JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

We are required to write a JavaScript function that takes in a number as one and the only argument. The function should then return a randomly generated string of the length specified by the argument.

The character set to be used for the string generation should only contain uppercase and lowercase alphabets (no whitespaces, punctuations or numerals).


The code for this will be −

const num = 13;
const randomString = (len = 1) => {
   const charSet =
   let randomString = '';
   for (let i = 0; i < len; i++) {
      let randomPoz = Math.floor(Math.random() * charSet.length);
      randomString += charSet.substring(randomPoz,randomPoz+1);
   return randomString;


And the output in the console will be −


The output is likely to differ in each run.

Updated on 21-Nov-2020 10:07:49