If I declare a variable in a function using var
then a slot for that variable is added to the LexicalEnvironment
defined by that function.
Questions like this are best be answered by looking at the spec:
Block : { StatementList }
- Let oldEnv be the running execution context’s LexicalEnvironment.
- Let blockEnv be NewDeclarativeEnvironment(oldEnv).
- Perform BlockDeclarationInstantiation(StatementList, blockEnv).
- Set the running execution context’s LexicalEnvironment to blockEnv.
- Let blockValue be the result of evaluating StatementList.
- Set the running execution context’s LexicalEnvironment to oldEnv.
- Return blockValue.
NOTE: No matter how control leaves the Block the LexicalEnvironment is always restored to its former state.
So what happens here?
When the block is evaluated, a new lexical environment is created, with the current lexical environment as "parent". The new environment replaces the current environment for the duration of evaluating the block.
If I use a block-scoped declaration, how is the surrounding
LexicalEnvironment
affected?
Other than it is temporarily replaced, it is not affected at all.