13 - conclusion 'SyntaxError: Unexpected token {'


#1

Hi, I wanted to do something to practice arrays, for loops, ifs etc. This is meant to check a username and password against arrays of usernames and corresponding passwords. There is an unexpected '{' somewhere and I just don't now what I have done wrong. There are some other bits I'm not sure about as well, like getting a function to call itself again - i'm not sure why it wouldn't work but it sort of feels wrong.

var userNames = ["user1", "user2", "user3", "user4"];
var passWords = ["password1","password2","password3","password4"];
var nameInput = prompt ("please enter your user name");
var pwordCorrect = false;
var listPosition = 0;
//function to see if username is in the list
var nameCheck = function(name){
for (i = 0; i < userNames.length; i++){
if (name === userNames[i]) {
listPosition = i;
return true
}
}
}
// function to check password matches string in same spot of the password array.
var pwordCheck = function(pword){
if (pword === passWords[listPosition]) {
console.log("you would now be logged in"); //test text
} else {
confirm("that username/password combination doesn't match");
for (a = 0; a < 3; a++) {// three attempts on password
pwordInput = prompt ("please enter your password");
pwordCheck(pwordInput);// rerun pword chek
}
}
}
// run programme starting with username check
for (b = 0; b < 3; b++){//three attempts
if (nameCheck(nameInput) { //is name on the list?
var pwordInput = prompt ("please enter your password");
pwordCheck(pwordInput); //if so run password check function
} else {
console.log("false");// test indicator, try again
var nameInput = prompt ("please enter your user name");
}
}


#2

on
"if(nameCheck(nameInput){"
You forgot the last )
You also should add a way so it will stop otherwise it will just show alerts forever :smile:


#3

Brilliant, thank you. I was at the for ages. I thought it would stop after three failed attempts. I think I need to look at that again.


#4

Also, in your for loops it's better to do
for(var a = 0; a < 3; a++)
Because if you leave out the var it makes the variable global which means I can access that variable, and so if you ever wanted to use a again it might be glitchy, so it's good to get used to using
var in your for loops :smile:


#5

I was wondering about that, which is why I gave them different names, initially I called them all 'i'. If you use var can you still reset or change the counter from outside of the function, or would it reset itself every time you leave that loop and go back into it.

Does that all make sense? I think i've worded it badly but I am new to this! If you use a function on 2 separate occasions, will a for loop inside it have reset itself automatically or does it need to e written in somewhere else?