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

What is the difference between code block in function and while loop?

I intuitively wanted to add keyword 'var' before 'secret' within the while loop. After going back to the 'JavaScript Basics, Variable Scope' video, I believe that I am confusing the idea of scope and/or code blocks in functions and code blocks in loops. Why am I able to omit the 'var' keyword in the loop code block, and not a function code block?

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

while (secret !== 'sesame') {
  secret = prompt('Please enter the pw again.');
}

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>

1 Answer

This is a pretty good question and got me thinking about scope more thoughtfully. Found this by digging around in Stack Exchange and MDN.

Important: JavaScript does not have block scope. Variables introduced with a block are scoped to the containing function or script, and the effects of setting them persist beyond the block itself. In other words, block statements do not introduce a scope. Although "standalone" blocks are valid syntax, you do not want to use standalone blocks in JavaScript, because they don't do what you think they do, if you think they do anything like such blocks in C or Java.

I remember Andrew talking about this, but this is a solid description too.

here's the link to the relevant MDN section. Hope this is relevant :] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/block

I guess I was confusing the idea of scope, and thought that a local scope was something that also existed within loops! Thanks for your time!