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

Should I think about global scope, and its effect here?

Hello,

On previous videos we talked about global and function scopes. Is "while" loop a function?

Because when i use guess or var guess inside the while loop, both works. How should we consider the scope effect on the loops. Is there any effect

Loops such as the while loop are control structures.

Great question, I was wondering the same. sleconte does this mean that it is ok to use global variables for control structures, or should we be using a variable inside of the loop as asli ari asks?

3 Answers

I think most will advise to avoid using global variables http://wiki.c2.com/?GlobalVariablesAreBad

Aakash Srivastav
seal-mask
.a{fill-rule:evenodd;}techdegree
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,638 Points

JavaScript doesn't have block scope, just function scope.
From 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.

By ES6 , let and const do have block scope. So if you use let instead of var in the while loop , result would be different. Hope it helps :) . Happy Coding Asli

i think it is the same as function because if we declare a counter outside the loop scope that matches another variable outside te loop body that how would the interpreter be able to differentiate between them ?