Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript JavaScript Loops, Arrays and Objects Simplify Repetitive Tasks with Loops Create a `do...while` loop

Challenge Task 1 of 1, javaScript Loops, Arrays, objects

Hi guys, guys I figured it out how the way that the Challenge asked, but my question here is, how can `I do it with (if) method. When i did it, it gave me (try again!).

script.js
var secret;
//secret = prompt("What is the secret password?");
var user = secret;

var correctPass = false;
do {
   secret = prompt("What is the secret password?");
    if (user === "sesame") {

        correctPass = true;
    } else {
        alert("wrong password")
    }
} while (!correctPass)

document.write("You know the secret password. Welcome.");
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="script.js"></script>
</body>
</html>

2 Answers

Umut İnanç
PLUS
Umut İnanç
Courses Plus Student 818 Points

It can be like in this example but its useless basically, because It asks for the password, If you dont answer it correctly, the program immediately terminates. The only way I can see is using a function that repeats itself.

var secret;
secret = prompt("What is the secret password?");

if (secret === "sesame") {
  document.write("You know the secret password. Welcome.");
} else {
  alert("Wrong password!")
}

We created a function below named passwordChecker. Everytime its called, It asks for an input and checks if its "sesame". If it's "sesame", the program simply prints "You know the secret password. Welcome." to the screen and terminates there. If it's not "sesame", it says "Wrong password!" and starts from the beginning of the function.

function passwordChecker(){

  var secret = prompt("What is the secret password?");

  if (secret === "sesame") {
    document.write("You know the secret password. Welcome.");
    return true;
  } else {
    alert("Wrong password!");
    return false;
    passwordChecker();
  }

}

passwordChecker();

I am not aware of javascript course topics but if you haven't seen functions yet, you can always come back and check.

Thank you, Umut İnanç, for helping me.