Reputation: 19
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);
Upvotes: 0
Views: 53
Reputation: 23858
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)
Upvotes: 1
Reputation: 189
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
Upvotes: 1