Generate Random String – JavaScript Solution

This is a preview lesson
Register or sign in to take this lesson.

Generate Random String

This tutorial shows a snippet for generating random string from a given set of characters.

Pseudo-code

let randomStringSize = 5   // length of finally generated random string
result = ' '  // placeholder for the final generated random string

characters = 'abcdefghijklmnopqrstuvwxyz123456789'  // Character set for random string

let characterLength = characters.length;  // geting the total length of characters

for ( let i = 0;  i < randomStringSize;  i++ ) {  // looping through the size of randomStringSize
      result += characters.charAt(Math.floor(Math.random() *  charactersLength))
 }

print (result)  // prints 5 characters long random string

// Math.random generates random floating point number in range from 0 to 1
// when the received number is multiplied with character length
// Math.floor removes the floating point from the multiplication between (Math.random * characterLength)
//  charAt method takes the character from the point in string
// and it is finally appended to the result

JavaScript Syntax

let result = '';
let length = 5;
let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
let charactersLength = characters.length;
for ( let i = 0; i < length; i++ ) {
    result += characters.charAt(Math.floor(Math.random() * charactersLength));
}

console.log(result);
/*
 * Output 
 * COULD print: MjdF6
 * COULD print: xAavF
*/

Now, the same code wrapped inside a function looks like

// function that generates random string
function generateRandomString(length) {
    let result  = '';
    let characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    let charactersLength = characters.length;
    for ( let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * charactersLength));
   }
   return result;
}

console.log(generateRandomString(5));

console.log(result);
/*
 * Output 
 * COULD print: MjdF6
 * COULD print: xAavF
*/