0

I'm making a random password generator in Vannila JS , I'm facing a unknown problem in following code :

function generatePassword(lower, upper, number, symbol, length) {
  let generatedPassword = "";
  const typesCount = lower + upper + number + symbol;
  const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter(
    (item) => Object.values(item)[0]
  );

  // Doesn't have a selected type
  if (typesCount === 0) {
    return "";
  }

  // create a loop
  for (let i = 0; i < length; i += typesCount) {
    typesArr.forEach((type) => {
      const funcName = Object.keys(type)[0];
      generatedPassword += randomFunc[funcName]();
    });
  }

  const finalPassword = generatedPassword.slice(0, length);

  return finalPassword;
}

In this block of code specifically the Object.values(item)[0] doesn't work if I enclose the statement in Curly Braces {} :

const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter(
    (item) => Object.values(item)[0]
  );

I don't understand why this is happening , I tried searching docs but no avail , Thanks !

  • What error are you getting now without curly braces? – palaѕн Apr 12 '20 at 07:52
  • I checked the console but I doesn't seem to give error when I enclose it in curly braces , but the code doesn't work either... But If the curly braces are removed code works just fine – Yash Kadam Apr 12 '20 at 07:54
  • Do you mean it doesn't work if you write `const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter( (item) => { Object.values(item)[0] } );` – Shubham Khatri Apr 12 '20 at 07:54
  • Exactly , It doesn't work this way & doesn't even show any errors – Yash Kadam Apr 12 '20 at 07:56
  • `.filter( (item) => Object.values(item)[0] );` what are you trying so in this code. Did you mean to use `.map()` method, because filter is used to filter an array and then return that value not to return a specific value. – palaѕн Apr 12 '20 at 07:59

1 Answers1

1

In order for Filter function to correctly work, it needs to return. a truthy of falsy value.

When you write it like

const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter(
    (item) => Object.values(item)[0]
  );

The result is implicitly return ie. Object.values(item)[0] is a returned value

However if you write it like

const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter(
    (item) => { Object.values(item)[0] }
  ); 

You haven't returned any value from the filter function, you would need to add a return statement for it like

const typesArr = [{ lower }, { upper }, { number }, { symbol }].filter(
    (item) => { return Object.values(item)[0]; }
);
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • if you can answer this https://stackoverflow.com/questions/61204297/best-way-to-pass-parameters-in-onclick-handler please – Dark Knight Apr 14 '20 at 09:26