dimanche 9 février 2020

How can I change these if statements into a switch statement? (javascript) [duplicate]

So I have this variable with prompt that is run when a function is executed. Can someone help me to change the if statements into switch statements to make the code look a little cleaner? Also can someone explain to me what the return; means? Thanks!

var length = parseInt(
    prompt('How many characters would you like your password to contain?')
  );

  if (isNaN(length) === true) {
    alert('Password length must be provided as a number');
    return;
  }

  if (length < 8) {
    alert('Password length must be at least 8 characters');
    return;
  }

  if (length > 128) {
    alert('Password length must less than 129 characters');
    return;
  }   

I tried doing the switch statement below but it didn't work. Can anyone help? (this is all inside a function by the way)

switch(length) {
  case (isNaN(length) === true):
  alert('Password length must be provided as a number');
  break;

  case length < 8: 
  alert('Password length must be at least 8 characters');
  break;

  case length > 128:
  alert('Password length must less than 129 characters');

}

Aucun commentaire:

Enregistrer un commentaire