Search code examples
javascriptecmascript-5ecma262

Clarity on the difference between "LexicalEnvironment" and "VariableEnvironment" in ECMAScript/JavaScript


Could someone clarify what the difference is between these two, as they exist in the Execution context? It's hard for me to read the ECMA 262 v 5 specification and clearly see the difference.

Thank You,


Solution

  • Both are components (of the same type) of Execution Contexts, but they serve distinct purposes (from the spec):

    LexicalEnvironment

    Identifies the Lexical Environment used to resolve identifier references made by code within this execution context.

    VariableEnvironment

    Identifies the Lexical Environment whose environment record holds bindings created by VariableStatements and FunctionDeclarations within this execution context.

    The next paragraph explains why they need to be different:

    When an execution context is created its LexicalEnvironment and VariableEnvironment components initially have the same value. The value of the VariableEnvironment component never changes while the value of the LexicalEnvironment component may change during execution of code within an execution context.

    That does not happen often and usually both refer to the same Lexical Environment. A good example for a changing LexicalEnvironment is given in the question Why do catch clauses have their own lexical environment? - see §12.14. The other place I could find in the spec where this happens are With Statements (§12.10) where an Object Environment Record is dynamically used for the identifier resolution - yet variable/function declarations are static.