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?


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.

razmig pulurian
razmig pulurian
Pro Student 23,888 Points

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

Aakash Srivastav
Aakash Srivastav
Full Stack JavaScript Techdegree Student 11,616 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 ?