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

Why is the syntax error ?

.

app.js
var secret = prompt("What is the secret password?");
while(secret === 'sesame')
{document.write("You know the secret password. Welcome.");}
else
{prompt("what is the secret password?");}
index.html
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript Loops</title>
</head>
<body>
<script src="app.js"></script>
</body>
</html>
Matthew Panton
Matthew Panton
15,228 Points

Hi, a while statement is used for loops and cannot be followed by an else clause. I'm not sure what the aim of this code challenge is but this might be the thing to do

var secret = prompt("What is the secret password?");
while (secret != 'sesame'){
    secret = prompt("what is the secret password?");
}
document.write("You know the secret password. Welcome.");

3 Answers

Matthew Rigdon
Matthew Rigdon
8,223 Points

Well your code doesn't do what you intended it to. While loops are used to continually cycle over a segment of code. Matthew Panton shows how you could use your while loop to continue asking the question about the secret password.

Right now your code will ask the question, and if it correct, it will keep printing out that you are correct, since you told it to use a while loop. The code will continue to run until you end it. If the password is wrong, it will print out that the password is wrong.

I don't see any syntax errors, other than maybe your spacing inside of the HTML code. I believe it is flagging the question as erroneous due to a continuous while loop.

Matthew Panton
Matthew Panton
15,228 Points

With regards to Matthew Rigdon's answer, there is a syntax error in the original code because you cannot use an "else" statement without an "if" statement before it.

The problem was the else , thank you both guys !