-3

I am running the following JavaScript code:

// Return true if the given username and password are in the database,
// false otherwise.
function validCredentials(enteredUsername, enteredPassword) {
   
   // Database of usernames and passwords
   let usernames = ["smith",  "tron",      "ace",      "ladyj",    "anon"];
   let passwords = ["qwerty", "EndOfLine", "year1942", "ladyj123", "PASSWORD"];
   
   // Search the usernames array for enteredUsername 
   
   // Only return true if the enteredUsername is in username, and the
   // same location in passwords is enteredPassword
   if (usernames.includes(enteredUsername)){
      var correctPassword = passwords[usernames.indexOf(enteredUsername)];
      if(enteredPassword == correctPassword){
         return true;
         }    
      }
      else {
         return false;
      }  
}


console.log("Login for ladyj: " + validCredentials("ladyj", "ladyj123"));  // true
console.log("Login for ace: " + validCredentials("ace", "wrong"));  // false
console.log("Login for jake: " + validCredentials("jake", "???"));  // false

I am expecting console.log("Login for ace: " + validCredentials("ace", "wrong")); return false, but it returned undefined. Can anyone tell me what went wrong?

  • 3
    `if(enteredPassword == correctPassword) { return true; }` does not have a corresponding `else` that returns false – CertainPerformance Jan 21 '23 at 17:26
  • 2
    This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? – David Jan 21 '23 at 17:26
  • 1
    You should let your IDE format the code for you, then it becomes obvious the ifs do not happen where / when you expect them to. – luk2302 Jan 21 '23 at 17:28

1 Answers1

1

You don't return in all possible branches (namely, if the username exists, but the password is incorrect). Move the return false outside the else to be the final statement in the function.

Alternatively, you could simplify the chain of if and else into one statement:

return usernames.includes(enteredUsername) && 
       passwords[usernames.indexOf(enteredUsername)] === enteredPassword;
Unmitigated
  • 76,500
  • 11
  • 62
  • 80