Hi I just started learning JS and I gut stuck on this part of the loop:
I cant find a way to make it loop 3 times and then block you. or open the site after once or 2 times that i do the wrong password.
it always just does one of this tow (depending on how I change the code)
1:
Enter your username:
+
Enter your password:
Then it loops 3 times
you have 3 more atempts…
you have 2 more atempts…
you have 1 more atempts…
Then it loops forever
"You have no more atempts"
2:
Enter your username:
+
Enter your password:
Then it loops 3 times
you have 3 more atempts…
Enter your username:
+
Enter your password:
you have 2 more atempts…
Enter your username:
+
Enter your password:
you have 1 more atempts…
Enter your username:
+
Enter your password:
Then it loops forever
"You have no more atempts"
var database = [
{
username: "refael",
password: "123456"
},
{
username: "boby",
password: "ilovepizza"
},
{
username: "sally",
password: "123"
}
];
var newsfeed = [
{
username: "bob",
timeline: "i love pizza"
},
{
username: "andy",
timeline: "im at the pool!"
}
];
function isUserValide(username, password){
for (var i=0; i < database.length; i++){
if (database[i].username === username &&
database[i].password === password) {
return true;
}
}
return false;
}
function singin(username, password) {
for (var atempts = 2; atempts >= 0; atempts--) {
if (isUserValide(username, password)) {
console.log(newsfeed);
alert("SuccessFully Logged In");
return true;
} else if (atempts==0) {
for (var i = 3; i >= 0;) {
alert("Too many atempts");
}
} else {
alert("You have "+atempts+" atempts left")
var usernameprompt = prompt("Enter your username")
var passwordprompt = prompt("Enter your password")
isUserValide(username, password)
}
}
}
var usernameprompt = prompt("Enter your username")
var passwordprompt = prompt("Enter your password")
singin(usernameprompt, passwordprompt);
2
Answers
This
else
block isn’t actually doing anything:Its logic is:
isUserValide
on the same original values (even though we already know the result, since those values haven’t changed) but never uses the result of that functionI suspect you meant to update those values before going through the loop again?:
As an aside…
let
andconst
for more intuitive control over your variable scopes and assignments.In this loop, you have error because loop has no condition. So it works endlessly.
You must write:
I’m not a JS programmer, but I think this is correct):