Need help! Javascript

Hi! I am working on this password generator solo project .I got to make the passwords but the generated passwords keep accumulating instead of resetting and displaying a new set of passwords. Please help :sob: :sob:. I cant figure out where i went wrong.

Thanks in advance!
Here is my codepen link →
A Pen by Ziana109 (codepen.io)

  let pwArray1 = []
  let pwArray2 = []
  let pwArray3 = []
  let pwArray4 = []

appear to be in a global scope. Maybe it is concatenating to array every time generate is called

Yeah. You can either clear them at the top of the generate function, or you can, when building the password string, instead of concatenating, place them at the index using your loop variable.

2 Likes

placing the pwArray’s inside your generate() function and adding the passwordEl methods in its designated loop should fix your problem

1 Like

thank you so much ! that soved it :heart:

1 Like

Just to be clear, a better design would be to have your generate function return a string that gets assigned in your variable (you’d do it 4 times, or maybe have them in an array) and then those get passed to your render function. I’d wrap that all in a function like “getNewPasswords” and just call that. Try to avoid global variables. They’re often trouble.

2 Likes

Hey Kevin, could you show an example of what that looks like?

You’re welcome. Good job though. :+1:t6: I just started JavaScript and had gotten stuck on that same issue.

Sure. I wrote this out, based on what you had. Basically I just applied some principles of functional programming. In retrospect, I may have jazzed it up too much, using too much ES6 and stuff. But this is pretty close to how I would have done it. It tightens it up and removes some of the repetition. The functions don’t require any global variables (except for constants in SCREAMING_SNAKE_CASE) and they have no side effects (they don’t mutate any variables outside of their scope . I think it is more readable this way, too. It’s just a different way of thinking, it takes practice.

const CHARS = [
  ...'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
  ...'abcdefghijklmnopqrstuvwxyz',
  ...'!@#$%^&*',
  ...'1234567890',
]

const ELEMENTS = [
  document.getElementById('password1'),
  document.getElementById('password2'),
  document.getElementById('password3'),
  document.getElementById('password4'),
]

const EMPTY_ARRAY = new Array(12).fill(null)

const generatePasswords = () =>
  ELEMENTS.forEach(
    el => el.textContent = generatePasswordString()
  )

const generatePasswordString = () =>
  EMPTY_ARRAY.map(
    c => CHARS[Math.floor(Math.random()* CHARS.length)]
  ).join('')
1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.