George Irimiciuc
George Irimiciuc

Reputation: 4633

Variable scope in loops

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?

Upvotes: 2

Views: 55

Answers (3)

elixenide
elixenide

Reputation: 44851

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.

Upvotes: 4

Alnitak
Alnitak

Reputation: 340055

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.

Upvotes: 4

Fabien Papet
Fabien Papet

Reputation: 2319

You are wrong, loops do not have scopes.

Upvotes: 2

Related Questions