April 25, 2024

Answer to JavaScript Password Exercise Q8

 

/*
This function simply returns a boolean value in response to the dialogue confirmation
*/
function checkEnter()
{
  return confirm("Do you wish to enter a password?");
}
/*
This function will accept a string as its argument. If the string is a single
space character, the function will return true,
else it returns false
*/
function isSpace(str)
{
  if (str == ' ')
  {
    return true;
  }
  else
  {
    return false;
  }
}
//A neater approach to writing this function is
//to return the result of the condition in a single line
function isSpace(str)
{
  return (str == ' ');
}
// ************ main program ************
var password , numOfChars, i , isOK;
if (checkEnter())
{
  password = window.prompt('Enter a password, no spaces please!' , '');
  numOfChars = password.length;
  //i references the index of each character in the string
  //JavaScript strings start at 0
  i= 0;
  //initialise a flag, this will help start the loop
  //and stop it if a space is detected
  isOK = true;
  while ((i < numOfChars)&& isOK)
  {
    if (isSpace(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!');
  }
}//end of outer if branch
else
{
  window.alert("Access denied.");
}

Notes:

  • A for loop could be used instead of a while loop.
    for(var i=0;(i < numOfChars) && isOK; i = i + 1)
    {
      if (password.charAt(i) == ' ')
      {
        isOK = false; // the loop will terminate
      }
    }
  • As far as M150 is concerned, a while loop will always do the job of a for loop. This is not always the case when programming with JavaScript. Go here to read about the continue, which is not taught on M150.

 

Back « JavaScript password exercises

 

 

 

 

 

 

 

 

Up to top of page