I am learning scopes and execution contexts. After reading lots of articles, I realize that there are generally two types of explanation. Each execution context consists of two phases: the creation phase and the execution phase.
Explanation 1:
In the memory creation phase, the JavaScript engine allocates memory to variables and functions in a so called memory stack. In the code execution phase, the JavaScript engine executes the code line by line. The visual representation for this kind of explanation normally looks like this:
(https://i.sstatic.net/lGk1bpv9.png)
Explanation 2:
When the JavaScript engine scans a script file, it creates an environment called the Execution Context. There are two types of execution contexts: a global execution context and a function execution context. When the JavaScript engine executes a script for the first time, it creates the global execution context and there’s only one global execution context, whereas a new function execution context is created on each function invocation. To keep track of all the execution contexts, the JavaScript engine uses the call stack (or sometimes called the execution context stack). Each execution context has a lexical environment associated with it that holds identifier-variable mapping. The explanation goes on……
The visual representation for this kind of explanation normally looks like this:
(https://i.sstatic.net/gNCK8oIz.png)
I have come up with 2 conclusions, which are:
- For the sake of simplicity, some just refer ‘lexical environment’ as ‘memory’.
- ‘Lexical environment’ and ‘Memory (Stack)’ are 2 different things. Memory is the actual space for storing data, and lexical environment is a conceptual structure within each execution context, and is used to manage scopes and identifier bindings.
Assume there is this code:
var ninja ="Muneyoshi";
function skulk(){
var action ="skulking";
function report(){
var intro = "Aha!";
}
report();
}
skulk();
What happens behind the scene is:
Phase 1
Phase 2
narutoshippuden is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.