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 it not valid if I add a var inside the while loop?

I know the answer is: 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.");

But why can't I have it be: var secret = prompt("What is the secret password?");

while ( secret !=== "sesame" ) { var secret = prompt("What is the secret password?"); }

document.write("You know the secret password. Welcome.");

In other words, why don't I call the var secret inside the while? Does it have to do with scope?

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

while ( secret !=== "sesame" ) {
  var secret = prompt("What is the secret password?");
}

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

hey there !

not in javascript only, it's in all languages, and David Brenecki its not about Treehouse, but you cant declare the same variable in and outside the loop. cause when you are typing the keyword " var " you are declaring a NEW variable and you are affecting a value to that variable, so if you reput the keyword " var " with the same name inside a loop, it will confuse the compiler system, since you are duplicating a variable, so either you declare a new variable with a new name, or you just use your variable without the keyword " var ".

PS : in this precise example, you can't declare a new variable, you d only use " secret = prompt(...) " , cause you need to check it's value each time the loop itirate !

cheers

I'm talking about declaring it only inside the loop. Not both

Thanks guys! Got it. Appreciate your help.

I think declaring a var in or outside a loop has to do with best coding practices and yes the scope. Declaring inside a loop a code block can still work but it is not optimized. If you get an error when declaring inside the loop its probably because Treehouse are trying to instill good coding practices into their students.

I think there are some cases though where declaring inside a loop is better