The ECMAScript 5 spec states the following:
Usually a Lexical Environment is associated with some specific syntactic structure of ECMAScript code such as a FunctionDeclaration, a WithStatement, or a Catch clause of a TryStatement and a new Lexical Environment is created each time such code is evaluated.
If my understanding is correct, then when a new Lexical Environment is created in JavaScript, a new scope is entered, which is why variables declared inside a function are not visible outside of that function:
function example() {
var x = 10;
console.log(x); //10
}
console.log(x); //ReferenceError
So in the above function declaration, a new Lexical Environment is created, which means x
is not available in any outer Lexical Environments that may exist.
So the part of the quote above about Function Declarations seems to make sense. However, it also states that a new Lexical Environment is created for the Catch clause of a Try Statement:
try {
console.log(y); //ReferenceError so we enter catch
}
catch(e) {
var x = 10;
console.log(x); //10
}
console.log(x); //10 - but why is x in scope?
So how does the scope of a catch
block work? Do I have a fundamental misunderstanding of what a Lexical Environment is?