How to generate a random string using JavaScript?

/ #JavaScript

A random string can be used for a lot of different purposes like password, filename, etc. But how do you generate one?

Let's begin with an example

function generateString(length) {
    var res = '';
    var availableChars = 'abcdefghijklmnopqrstuvwxyz';
    var numAvalailableChars = availableChars.length;

    for (var i = 0; i < length; i++) {
        res += availableChars.charAt(Math.floor(Math.random() * numAvalailableChars));

    return res;

var password = generateString(8);


If you run this code in your browser, you will see a random string in your console.

Let me explain what I've done:
1) I started by creating a function called "generateString" with one parameter. This parameter is the length of the string you want to generate.
2) The variable "availableChars" is just a regular string. This can be simpler, it can contain large letters and numbers too. The string just pick one random character from this string.
3) I make a for loop and for each iteration (0 to the length of "length") i add one letter to the result I'm returning. I use "charAt" to get the character at the random position from Math.floor/random.
4) The reason I'm using both Random and Floor is that this is needed to get a integer.
5) After the function, you can call "generateString" as many times as you want, just remember to pass in a length.


No comments yet...

Add comment


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.