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 A Closer Look At Loop Conditions

Jacob Tennyson
Jacob Tennyson
6,240 Points

I be strugglin..

help

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

while(secret !== 'sesame'){
  prompt();
  secret = ('sesame');

}
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="app.js"></script>
</body>
</html>

2 Answers

Gunhoo Yoon
Gunhoo Yoon
5,027 Points

First it's always good to think before coding. So here's process.

Goal:e From web page, prompt user for secret word and react to it.

  1. How to prompt user?: use prompt() function. prompt("message") shows small input box with a message and stores the response.

  2. How to validate?: use comparison

  3. Should I keep asking user?: if yes use while.

  4. Should I let user know what happened?: yes.

//1
//Ask for first time.
var secret = prompt("What is the secret password?");

//2, 3
//Keep asking until user tell what we want.
while ( secret !== "sesame") {
    //Notice the slight difference in actual message
    secret = prompt("Try again. What is the secret password?")
}

//4
//At this point user got out of loop which means they got the secret.
document.write("Welcome")
//Alternative.
var secret;
do {
  secret = prompt("What is the secret password?")
} while (secret !== "sesame")

document.write("Welcome")
Abe Layee
Abe Layee
8,378 Points

You're so close but the is no need to repeat secret twice and call the prompt() method inside your code.

var secret; // declare a variable called secret.

while (secret !== "sesame") { // 
     secret = prompt("What is the secret password?"); // pass in the prompt()  to the secret variable.
}
document.write("You know the secret password. Welcome.");