What's the difference between LexicalEnvironment and VariableEnvironment in ES6?

87 views Asked by At

There was a similar question Clarity on the difference between “LexicalEnvironment” and “VariableEnvironment” in ECMAScript/JavaScript posted on SO two years ago, but it was based on ES5.

I'm learning ES6 now and encountered some fun facts. For example, in a block scope, you can't declare one variable with let more than once.

// you can declare a variable with var multiple times
var a = 1;
var a = 2;
a;     // => 2

// but you can't do that with let
{
    let a = 1;
    let a = 2; // => Error
} 

So I referred to the ES6 draft, and some sentences there caught my attention:

let and const declarations define variables that are scoped to the running execution context’s LexicalEnvironment.

A var statement declares variables that are scoped to the running execution context’s VariableEnvironment.

Well consider this:

// in global execution context
{
    let a = 1;
    var b = 2;
}
console.log(a);    // => ReferenceError: a is not defined
console.log(b);    // => 2

As we all know, the let declarations restrict the scope of variables in the block, but how should we understand the phrase **let** and **const** declarations define variables that are scoped to the running execution context’s LexicalEnvironment.?

Does the LexicalEnvironment here has something to do with the block?

0

There are 0 answers