mardi 26 juin 2018

Variable declaration inside 'if' statement

My question is potentially embarrassing. I'd consult google if I knew what question to ask specifically, but alas, I'm a code newbie and as such am not familiar with the jargon...

I'm following a written tutorial @https://javascript.info. I'm on the lesson about conditional operators and if statements, having trouble wrapping my head around the behaviour of one of the tasks (http://javascript.info/ifelse#tasks), specifically task #4. "Check the login".

Here's the code:

let userLogin = prompt("Who's there?", "");

if (userLogin == 'Admin') {

  let pass = prompt("Password?", ""); // *******    

  if (pass == 'TheMaster') {
    alert('Welcome!');
  } else if (!pass) {
    alert("Canceled.");
  } else {
    alert('I do not know you');
  }

} else if (!userLogin) {
  alert("Canceled");
} else {
  alert("I don't know you")
}

My question revolves around the (****) line. The code doesn't work properly if that line isn't nested in the 'if', which threw me way off ( had it as a "global" variable to begin with, had to check the solution because I couldnt find the bug ).

I ask of you, please, clarify why that is so. :(

Aucun commentaire:

Enregistrer un commentaire