Search code examples
javascriptloopsif-statementconditional-statementspasswords

How to give "No more tries left" in a password-guessing loop


I've just started learning JS and I got stuck here. What I need to do:

  • If you don't enter the correct password, you get the message "Try again".
  • If you don't enter the password 3 times, you get the message "No more tries left".
  • If you enter the correct password, you get the message "You may enter".

Here's my code:

for ( let i = 3; i > 0; i-- ) {
  let password = prompt("What is the password?")  
  if ( password.toUpperCase() !== "BINGO" ) {
    alert("Try again")
  } else if ( i = 0 ) {
    alert("No more tries left")
  } else {
    alert("You may enter")
  }
}

I can't get it work properly as the message "No more tries left" doesn't show up. I know ( i = 0 ) is wrong but I don't know how to make it work.


Solution

  • Firstly, make sure that you're not using an assignment operator when you check if i == 0. You're currently using i = 0, which doesn't check if the two are equal as much as it assigns the left to the right. No bueno.

    Secondly, your for loop is off just by a bit. It'll never get to 0 because you've asked it to loop while i > 0, not i >= 0. But wait - if you use i >= 0, it'll loop four times. That's not what you want either. We'll compromise and loop three times, but check if i == 1 instead of 0.

    Here's my corrected code that works:

    // loop three times
    for ( let i = 3; i > 0; i-- ) {
      let password = prompt("What is the password?") 
      // if it's the correct answer then alert and break the loop
      if ( password.toUpperCase() == "BINGO" ) {
        alert("You may enter")
        break
      // if it's not, and the tries has elapsed, then alert and break the loop
      } else if ( i == 1 ) {
        alert("No more tries left")
        break
      // if it's not but the tries have not elapsed, then loop again
      } else {
        alert("Try again")
      }
    }