I am trying to convert an array to string using array.join() or array.toString() but it’s not working as it’s supposed to work. When I console.log it stays as an array.
I’ve the intuition that this issue comes from something related to function scopes, but I could not figure it out yet.
The project I’m trying to build is a password generator.
JavaScript
x
21
21
1
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
2
const numbers = "0123456789";
3
const symbols = "!@#$%^&*_-+=";
4
5
const button = document.querySelector(".gen-pass");
6
7
button.addEventListener("click", (e) => {
8
9
let password = [];
10
11
for (let i = 0; i < 4; i++) {
12
let randomLetters = letters[Math.floor(Math.random() * letters.length)];
13
let randomNumbers = numbers[Math.floor(Math.random() * numbers.length)];
14
let randomSymbols = symbols[Math.floor(Math.random() * symbols.length)];
15
16
password.push(randomLetters, randomNumbers, randomSymbols);
17
password.join();
18
}
19
20
console.log(password);
21
});
JavaScript
1
1
1
<button class="gen-pass">Generate!</button>
Advertisement
Answer
Array.prototype.join() returns a string. It does not change the object it is called on.
You may want to create a new variable or mutate password
after the for loop has completed like so:
JavaScript
1
16
16
1
const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
2
const numbers = "0123456789";
3
const symbols = "!@#$%^&*_-+=";
4
let password = [];
5
for (let i = 0; i < 4; i++) {
6
let randomLetters = letters[Math.floor(Math.random() * letters.length)];
7
let randomNumbers = numbers[Math.floor(Math.random() * numbers.length)];
8
let randomSymbols = symbols[Math.floor(Math.random() * symbols.length)];
9
10
password.push(randomLetters, randomNumbers, randomSymbols);
11
12
}
13
14
password = password.join('');
15
16
console.log(password);