Consider the following excerpt from ECMA-262 v5.1 (which I recently saw in this question):
A Lexical Environment is a specification type used to define the association of Identifiers to specific variables and functions based upon the lexical nesting structure of ECMAScript code. A Lexical Environment consists of an Environment Record and a possibly null reference to an outer Lexical Environment. 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.
I thought that meant the body of catch
clauses would hoist its own variables like functions do, but apparently that's not the case:
var a = 1;
try {
console.log(x); // ReferenceError
} catch(ex) {
console.log(a); // 1, not undefined
var a = 3;
}
Does anybody know why? Also, why does a catch
clause need its own lexical environment?
catch
could have its own local variables, shadowing the globals. But it can't, because the Lexical Environment created for it is of another type (see Bergi's answer, and the spec at 10.3). – Persecute