Closures Continued: Lexical vs. Dynamic Scope
It is helpful to contrast lexical scope with dynamic scope to understand why closures work the way they do.
Lexical Scope (JavaScript)
Scope is determined by where the function is defined in the source code. The inner function "remembers" the environment where it was created.
Dynamic Scope
Scope is determined by where the function is called (the call stack).
Example Comparison
const value = "Global";
function printValue() {
console.log(value);
}
function wrapper() {
const value = "Local";
printValue();
}
wrapper();
- In JavaScript (Lexical):
printValuewas defined in the global scope, so it seesvalue = "Global". The output is "Global". - If JavaScript were Dynamic:
printValueis called insidewrapper, so it would seewrapper'svalue. The output would be "Local".
Closures rely on lexical scoping to persist data. If scope were dynamic, the data a function accesses would change depending on who called it, breaking the encapsulation that closures provide.
programming/javascript/vanilla/closures programming/javascript/vanilla/javascript