Search code examples
javascriptscopeecmascript-5ecma262

Does a function expression have its own scope/lexical environment


I'm reading the Execution Context / Lexical Environment section of the ECMA 262 5 specification. It states the following: (emphasis added)

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 noticed that it says nothing about creating a lexical environment for Function Expressions. Is a lexical environment created for function expressions, or is one created only for function declarations? Am I missing something?

Edit: I notice that function code will have its own execution context, which is why I'm also confused why function expression is not mentioned in the lexical environment section.


Solution

  • Yes, every function gets (§10.4.3) its own ExecutionContext when it is called (§13.2.1). That new context is initialised with a new LexicalEnvironment (created by NewDeclarativeEnvironment, §10.2.2.2), deriving from the [[Scope]] of the function - i.e. the LexicalEnvironment it was declared/"expressed" in (§13).

    As @Pointy pointed out, the sentence you stumpled upon does not exhaustively list them: "…some [structure] such as…".