How to get rid of this loop

Viewed 63

I've developed a simple login system in JS. When the password, the username or both are incorrect it's suposed to show an alert but now it shows 4. I know it is because of the for loop but I don't know how to get rid of it without breaking all the code. Thanks in advance =)

I leave here the piece of code:

function getName() {
      var user = document.getElementById('Username').value;
      var pass = document.getElementById('Password').value;
      
      for (let f = 0; f < arr.length; f++) {
        if (user == arr[f][0] && pass == arr[f][1]) {              
          document.write("Welcome back ", user, ", we've missed you");
        }
        if (user == arr[f][0] && pass != arr[f][0])  {
          alert("Your password is incorrect");
        }
        else if (user != arr[f][0] && pass == arr[f][1]) {
          alert("Your username is incorrect");
        }
        else {
          alert("Unnexistant account");
        }
      }
    }
3 Answers

Add break; after each document.write or alert statements.

If the username for one account is wrong, you don't want to tell them their account doesn't exist until you check it for every single account:

function getName() {
    var user = document.getElementById('Username').value;
    var pass = document.getElementById('Password').value;

    for (let f = 0; f < arr.length; f++) {
        if (user == arr[f][0] && pass == arr[f][1]) {              
            document.write("Welcome back ", user, ", we've missed you");
            return; // exit from the function since we've found an account
        }
        if (user == arr[f][0] && pass != arr[f][0])  {
            alert("Your password is incorrect");
            return; // exit from the function since we've found a username match
        }
    }
    // couldn't find match, alert
    alert("Your account does not exist.");
}

Your instinct is correct, and a for loop is probably not ideal here. It is hard to read and debug and it's also kind of ugly. If you want to stick with it, the other answers show you how.

Assuming arr is an array of usernames & passwords, you can convert this into a Map and remove your loop completely.

const map = new Map();
arr.map(e => m.set(e[0], e[1]));

try {
  if (map.get(user) === pass) {
    document.write("welcome back " + user + ", we missed you.");
  } else {
    // although this might be too much info from a security standpoint.
    document.write("incorrect password"); 
  }
} catch (e) {
  document.write("could not find user.");
}
Related