-1

I have a JS if/else question. Can I know why, if I enter the correct username and password, the else statement is also executed?

By right, if the username and password is correct, then only the if statement will be executed. How come both are executed? Code as below:

var database = [
  {
    username: "john83reuben",
    password: "12345"
  },
  {
    username: "jdominic",
    password: "12345"
  },
  {
    username: "johnreuban",
    password: "12345"
  }
];

newsfeed =[
  { username: "john83reuben", timeline: "Psalm 118:19. I will extol the Lord at all times; His praise will always be on my lips"},
  { username: "jdominic", timeline: "Psalm 34:1-3. I thank you, Lord, with all my heart; I sing praise to you before the gods."},
  { username: "johnreuban", timeline: "Psalm 138: 1-2. I will give thanks to the Lord because of his righteousness;"}
];

function signIn(user,pass){

  for(let i=0; i < database.length ; i++){
    if(database[i].username === user && database[i].password === pass ){
        console.log(newsfeed);

    }else{
      console.log("Error");
    } 

  }
}

var usernamePrompt = prompt("What is your username?");
var passwordPrompt = prompt("What is your password?");

signIn(usernamePrompt,passwordPrompt);

1
  • Because you run your if-statement for every object in your array, so when one of the objects don't match your if your else block will trigger Commented Sep 9, 2020 at 15:11

2 Answers 2

1

You are checking against the whole list of the database var, it will execute the else case when it matches against an item that does not have the right credentials, to avoid that just break out of the loop when you find the correct one

Sign up to request clarification or add additional context in comments.

1 Comment

Using break will still log "error" for all objects before a correct one is found.
1

Use Array.prototype.some method to find out if your user/pass at least matches once.

var result = database.some(item => {
   
    return item.userName === user && item.password === pass

})

console.log(result)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.