ekiyanov
ekiyanov

Reputation: 461

es6 What makes Block-Scoped Variables different?

Looking at http://es6-features.org/#BlockScopedVariables

What a difference between

for (let i = 0; i < a.length; i++) { let x = a[i] … }

and

for (var i = 0; i < a.length; i++) { var x = a[i] … }

I understand in example they move declaration of variables out of block

var i, x, y 
for (i = 0; i < a.length; i++) 
{ 
x = a[i] … 
}

but is there any reason for it ? why not to include declaration inside the block ? Is it a bad practice or performance hit ?

Just want to understand.

Thanks.

Upvotes: 1

Views: 75

Answers (2)

mattsven
mattsven

Reputation: 23283

The primary difference is scope.

Before ES6, you were stuck using var. When using var, variables were defined in the scope of the enclosing function. If there is no function, then they are defined on the global object (typically window). This made it difficult to have two variables named the same, but in different scopes without running into conflicts.

let helps to solve this problem by allowing you to scope variables to the enclosing block, like an if or for loop.

For example, one common issue was nested for loops:

for(var i = 0; i < 4; i++){ // loop 1
    console.log(i); // 0

    for(var i = 0; i < 4; i++){ // loop 2
    }

    console.log(i); // 4 - since i was changed by loop 2, loop 1 is now unstable and will skip
}

In the example above, the problem is eliminated using let instead - each i variable is scoped to it's own block.

As for any differences in performance, I can't say. If someone else knows, I'd love to know.

Upvotes: 2

Phil
Phil

Reputation: 164798

Block scoped variables are simply not available outside their containing block. This is easy to illustrate with an example

for (let i = 0; i < 2; i++) console.info('inner loop i', i);
try {
  console.info('after loop i', i);
} catch (e) {
  console.error(e.message)
}

for (var j = 0; j < 2; j++) console.info('inner loop j', j);
console.info('after loop j', j);

Upvotes: 4

Related Questions