2

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?

3
  • Javascript only knows object scope and function scope. There's no block scope. Commented Jul 11, 2014 at 8:46
  • 1
    Variables have function level scope, not block level... Commented Jul 11, 2014 at 8:46
  • Ah, now I understand. Commented Jul 11, 2014 at 8:46

3 Answers 3

4

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

I know, the scope is the same as the one in which they were created. Maybe I'm wrong?
Yes, you're wrong. If you do 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).
2

You are wrong, loops do not have scopes.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.