0

im a early student and im trying to learn Javascript by myself since in university i only have C. As a side-project im trying to do a password generator, i want to know what are viable ways of generating a random array with elements of other already declared arrays. In other words, i have these arrays:

let upperCase = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] ;
let underCase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] ;
let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ;

how would you approach this in Javascript? is it correct to just google some fusion function which mixes everything up or is there a better way? Take in mind that i should be able to constantly press this button and get a new array. They're in different arrays because i want to add the function to choose whether the password has uppercase/numbers/symbols or not.

4
  • Well first of all, how would you do it in C? Not the literal code you would write, but the steps and logic you would need to complete the task. Commented Jul 17, 2022 at 4:50
  • @hhearts hey! what i thought was doing multiple functions for each category(since the user chooses which ones to add to the password) and overwrite random positions of the array with random positions of the other array, for ex (pass[2] = upperCase[4]) until every position of the pass array is != to '\0'. But not only do i have this feeling this is a overly-complicated way of doing it, i sense its not optimal.. maybe im wrong lol but when i chose this as a side-project it was because in my head it was simple. Commented Jul 17, 2022 at 4:57
  • Hmm well it sounds like it would work but couldn't you just use a loop and inside the loop add onto a string with a random character from an array? Commented Jul 17, 2022 at 5:20
  • but how do you add onto? im new to javascript is there a way to just add things to an array outside its first size, hence increasing its size at the same time? Commented Jul 17, 2022 at 5:24

3 Answers 3

2

Since you are newer to JavaScript, let's do it the simplest way. Not the fastest, or shortest way, but the simplest, easiest to understand way.

I believe that combining these arrays:

let upperCase = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] ;
let underCase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] ;
let numbers = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ;

into just one:

let chars = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ;

will make our job simpler. There is no need to choose a random array and then a random character now. It's just simply choosing a random character.

Now we set an arbitrary length of passwords we wish to generate. Let's say 8 for now.

let passwordLength = 8;

We'll need to store the generated password, so let's also make a variable for that:

let generated = "";

Simply put, we want to add random characters to this generated password however many times we stored in the password length. Sounds like we need a loop! We'll use a traditional C-style loop here:

for (let i = 0; i < passwordLength; i++) {

}

and inside the loop, we want to add a random character. This can be done in many ways, but the most common is this:

chars[Math.floor(Math.random() * chars.length)]

Because Math.random() generates numbers from 0 to 1 but excluding 1, we are making a range from 0 to chars.length, excluding chars. We only want integers, though, so we use Math.floor (functionally the same as stripping off the decimal part).

Then we use the random index to access the random character in the array.

Finally, we add the random character to the generated password:

generatedPassword += chars[Math.floor(Math.random() * chars.length)]

So when you're all done, it should look something like this:

let chars = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z", "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z", "0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ;

let passwordLength = 8;

let generated = "";

for (let i = 0; i < passwordLength; i++) {
  generated += chars[Math.floor(Math.random() * chars.length)];
}

console.log(generated);

If you run the snippet, you should see a random password of length 8!

References:

Sign up to request clarification or add additional context in comments.

1 Comment

Nice answer, I need one help if Possible. I asked one question yesterday but didn't got any answers yet. I possible can you please take a look into it.
1

Here is a quick and dirty password generator

// combine all possible characters in a singular array
const chars = [...upperCase, ...underCase, ...numbers];
const passwordLength = 24;

// create a new array with the length of 24 (24 is the length of your generated password)
const password = [...new Array(passwordLength)]
    // select random indices from the chars array and mutate the array with the randomly selected character
    .map(c => chars[Math.floor(Math.random() * chars.length)])
    // convert the array to a string by connecting each entry with ''
    .join('')

console.log(password) // <- e.g. 'VG9eNnUE7rmzapCNhYNgakg8'

But you wouldn't use the built-in Math.random() function for security reasons, it's better to use a cryptographically secure random number generator.

4 Comments

hey! thanks for the answer, im still learning javascript, what does .map do? thoug my biggest question is why do you add "...new" to array[24] ? does that mean something? also, i plan on adding a function where the user chooses the length of his password, is it possible to create a variable for that and use it instead of the 24?
For the time being you can just do It my way and not care about security for now as you are very new to JS. But once you are comfortable with the syntax try to write as concise code as possible. You can use w3schools.com/js/default.asp to learn JS in a very simple and easy to understand english.
Do you mind explaining your solution, more in-depth, for the original poster to understand? At the very least link references to the methods and functions used (probably MDN).
Of course you can use whatever positive integer value you want to use as your passwords length, I have edited the answer accordingly. As for what .map() does, ,map() is a higher order array function, you can learn about that here, ... is the spread operator, I am doing [...new Array()] to make the array iterable, you can learn about all of these on different websites.
-2

I hope this will do the trick:

You should do this method only to achieve this functionality and not in a real project as this is not secure. You can use OP answer for a more secure way of doing it.

function randomPassword() {
    const upperCase = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"] ;
    const lowerCase = ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"] ;
    const digits = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9"] ;
    
    let passwordSize = 5;
    
    let password = [];
    
    // with each iteration password size will decrease by 1 and when the value become zero we stop
    while (passwordSize-- > 0) {
        let randomArray = Math.floor(Math.random() * 4) + 1;
        if (randomArray == 1) {
            let randomUpperCaseCharacterIndex = Math.floor(Math.random() * 26);
            password.push(upperCase[randomUpperCaseCharacterIndex]);
        } else if (randomArray == 2) {
            let randomLowerCaseCharacterIndex = Math.floor(Math.random() * 26);
            password.push(lowerCase[randomLowerCaseCharacterIndex]);
        } else {
            let randomDigitIndex = Math.floor(Math.random() * 10);
            password.push(digits[randomDigitIndex]);
        }
    }
    
    return password;
}


console.log(randomPassword());

You can refer to this article to understand the function of Math.random().

7 Comments

Hey! i didnt do it lol, i tend to not vote at all. im still trying to read and understand the while loop, i have two questions, what does "passwordSize-- > 0" mean? why isnt it just "passwordSize > 0" ? also, the .push function im guessing it adds things to already declared arrays? like if you have let array ["0"] you push "1" and know its ["0", "1"], right? Thanks for the answer! :D
If you just passwordSize > 0 then the loop will never stop. Because here I want a password of size 5 so we need to loop only five times and for each iteration of loop we are adding new symbol in our password array. passwordSize-- is just a fancy way of saying passwordSize = passwordSize - 1
For the second question the answer is yes. .push() is used to add a new element to an array from the back(right side).
Please accept any of the answer if it worked for you. Click on the tick mark for the answer you want to accept.
oh wow im dumb i didnt realize its the opposite of ++! im not used to the syntax beeing so friendly! also, very very useful the .push function, in comparison to C this language seems too good to be true lol, thanks for the quick responses!! i marked it as an answer
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.