I am a bit confused http://jsfiddle.net/
{
for (var counter = 1; counter < 6; counter++) {
}
}
console.log(counter);
If variables from loops are available in the scope the for loop is created, then why do I have access to the variable one level higher, since I created another scope by putting those brackets?
-
Javascript only knows object scope and function scope. There's no block scope.Luaan– Luaan2014年07月11日 08:46:09 +00:00Commented Jul 11, 2014 at 8:46
-
1Variables have function level scope, not block level...T J– T J2014年07月11日 08:46:29 +00:00Commented Jul 11, 2014 at 8:46
-
Ah, now I understand.George Irimiciuc– George Irimiciuc2014年07月11日 08:46:47 +00:00Commented Jul 11, 2014 at 8:46
3 Answers 3
Variables created with the var keyword have function scope (or global scope if they're declared outside of a function).
ES6 introduces the let keyword for block scoped variables.
Comments
Loops do not have their own scopes.
A loop is a block, and blocks do not have their own scopes; variables created with var can only have function or global scope.
As others have pointed out, in ES6, you will be able to use block-scoped variables with the let keyword.
2 Comments
for(var counter = 1...), counter will be available from that point forward in the function containing this loop (or globally, if it is not in a function).You are wrong, loops do not have scopes.