March 28, 2024

Answer to JavaScript Password Exercise Q6

 

i)

var password , numOfChars, i , isOK;
password = window.prompt('Enter a password, no spaces please!' , '');
numOfChars = password.length;
/*
initialise i - this will reference the index of each character in the string
*/
i= 0;
/*
initialise a flag, this will be used as part of the condition to
start the loop and stop it if a space is detected
*/
isOK = true;
while ((i < numOfChars)&& isOK)
{
  if (password.charAt(i) == ' ')
  {
    isOK = false; // the loop will terminate
  }
  else
  {
    i = i + 1;
  }
}
//now check the flag
if (isOK)
{
  window.alert('Valid');
}
else
{
  window.alert('Invalid, contains a space!');
}

Notes:

  • The final else statement could be removed and the alert placed in the nested if statement where the flag has been set to false.
  • The code is set out in such a way as to illustrate the logic of the algorithm. Try and indent your code in order to provide structure; this will help anyone reading it.

 

Back « JavaScript password exercises

 

 

 

 

 

 

 

 

Up to top of page