ES5: LexicalEnvironment versus VariableEnvironment?

Allen Wirfs-Brock allen at
Tue Apr 19 10:21:30 PDT 2011

On Apr 19, 2011, at 9:37 AM, Axel Rauschmayer wrote:

> I hope this is the right place to ask this question:
> When are LexicalEnvironment and VariableEnvironment ever not the same? My understanding, derived from ECMA-262 is as follows:
> (1) Mainly needed for "with", because properties should be found during identifier lookup, but new bindings should be made in the surrounding environment.

also within catch clauses to provide a local binding  for the catch parameter

> (2) Function definitions: function declarations use the VariableEnvironment as scope, while function expressions use the LexicalEnvironment. Rationale? To make function declarations function-global (=ignoring with statements)?

ES5 doesn't allow for the occurrence of FunctionDeclarations in any contexts where the VariableEnvironment and LexicalEnvironment are different.  FunctionDeclarations are defined to be logically "hoisted" to the top of the enclosing VariableEnvironment.  However, the spec. language is such that if an implementation is extended to allow such declarations they would still be scoped to the VariableEnvironment.  FunctionExpressions are not "hoisted" so they are scope to the current LexicalEnvironment.  Hence they have visibility of bindings induced by with statements and catch clauses. 

> Did I miss any differences?
> The following code can be used to test (2). Console output is "bar" on Firefox and Rhino, "abc" on V8 (Node.js). If you use a function expression, the output is "bar" on all platforms.
> var foo = "abc";
> with({ foo: "bar" }) {
>    function f() {
>        console.log(foo);
>    }
>    f();
> }
Because the meaning of such a function declaration is not specified by ES5, the results can be implementation dependent.  Arguably the V8 result is closer to what the ES5 specification suggests (few changes to the spec. would be required to specify that result) but the FF result is probably closer to what a programmer would expect.


More information about the es-discuss mailing list