Explain the concept of lexical scoping
TL;DR
Lexical scoping means that the scope of a variable is determined by its location within the source code, and nested functions have access to variables declared in their outer scope. For example:
In this example, innerFunction can access outerVariable because of lexical scoping.
Name lookup follows source nesting
Lexical scope is determined where functions and blocks are written, so lookup walks outward through those enclosing environments.
The call site's scope is not searched, which is why passing a function elsewhere does not change which outer variables it captures.
Lexical scoping
Lexical scoping determines how variable names are resolved through the scopes enclosing the code. A variable's scope depends on its position in the source, and nested functions can access variables declared in their outer scopes.
How lexical scoping works
When a function is defined, it captures the scope in which it was created. This means that the function has access to variables in its own scope as well as variables in any containing (outer) scopes.
Example
Consider the following example:
In this example:
outerFunctiondeclares a variableouterVariable.innerFunctionis nested insideouterFunctionand logsouterVariableto the console.- When
innerFunctionis called, it has access toouterVariablebecause of lexical scoping.
Nested functions and closures
Lexical scoping is closely related to closures. A closure is created when a function retains access to its lexical scope, even when the function is executed outside that scope.
In this example:
outerFunctionreturnsinnerFunction.myInnerFunctionis assigned the returnedinnerFunction.- When
myInnerFunctionis called, it still has access toouterVariablebecause of the closure created by lexical scoping.
Further reading
- MDN Web Docs: Closures
- JavaScript.info: Lexical environment
- Eloquent JavaScript: Functions and closures