Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Trying to convert an Array to String (JavaScript)

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numbers = "0123456789";
const symbols = "!@#$%^&*_-+=";

const button = document.querySelector(".gen-pass");

button.addEventListener("click", (e) => {

  let password = [];
  
  for (let i = 0; i < 4; i++) {
    let randomLetters = letters[Math.floor(Math.random() * letters.length)];
    let randomNumbers = numbers[Math.floor(Math.random() * numbers.length)];
    let randomSymbols = symbols[Math.floor(Math.random() * symbols.length)];

    password.push(randomLetters, randomNumbers, randomSymbols);
    password.join();
  }

  console.log(password);
});
<button class="gen-pass">Generate!</button>

>Solution :

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:

const letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
const numbers = "0123456789";
const symbols = "!@#$%^&*_-+=";
let password = [];
for (let i = 0; i < 4; i++) {
    let randomLetters = letters[Math.floor(Math.random() * letters.length)];
    let randomNumbers = numbers[Math.floor(Math.random() * numbers.length)];
    let randomSymbols = symbols[Math.floor(Math.random() * symbols.length)];

    password.push(randomLetters, randomNumbers, randomSymbols);
    
  }
  
  password = password.join('');

  console.log(password);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading