🔰lexical environment
JS ⟩ concept ⟩ execution context ⟩ lexical environment
In JavaScript, every running function, code block {...}, and the script as a whole have an internal associated object known as the "lexical environment", it consists of two parts:
environment record – an object that stores
all local variable(s) as its properties.
other information like the value of this.
A reference to the outer lexical environment (associated with the outer code).
📗 JS.info ⟩ Lexical Environment
// make counter
function Counter() {
let count = 0;
return function() {
return ++count;
};
}
// a counter instance
let counter = Counter();
counter(), // 1
counter(), // 2🔸environment record - stores local variables/this ...
🔸[[Environment]] - reference to lexical environment where a function was made.
⭐closure - function that can access its outer lexical environment.
❗modify current scope at runtime❗️ - (actually) modify current lexical environment.
A "variable" is just a property of the environment record.
compilation creates a map of all the lexical scopes ... you can think of this plan as inserted code for use at runtime, which defines all the scopes (aka, "lexical environments") and registers all the identifiers (variables) for each scope. 📗 You Don't Know JS
Usually, a lexical environments is removed from memory with all the variables after the function call finishes.
The scope of a code block can reach all its parent's lexical environment so it can use its parent’s variable(s). In this way, we have a scope chain, chain of all parent’s scope.
⚖️scope chain is similar to lexical environments.
⭐lexical environment is part of execution context.
⭐closure closes over its outer lexical environment.
⭐declaration determines scope(s) at compile-time.
❗var (a statement)
Q:lexical environment === scope❓
A:my understanding is that
lexical environment is created at runtime, every time a scope is entered❗
Last updated