Scope Chain
Scope : Where a variable is available in your code and if its truly the same variable or a new copy
Example:
function b (){
console.log(myVar);
}
function a () {
var myVar = 2;
b();
}
var myVar =1;
a();
On Chrome Dev Console:
> 1
The value that was sitting at the global level (var myVar = 1)
Why?
Excecution stack:
b()
When we request a variable, JS look at more than its execution context,
Every execution context has a reference to its outer environment
(So in the case of function b, it is the Global Execution Context)
The Lexical Environment
Where something is written physically in your code is important,
determines important thing such as how the JS Engine will decide and interpret lives and how they sit in memory.
So where does function b sit?
On top of the Global Environment
(other word: it is not inside function a, it is sitting at the same level as var myVar = 1)
The order of execution matters, Javascript does something special,
it cares about the Lexical Environment when it comes to the outer reference where every execution context gets
When you ask for a variable in any execution context, if it cannot find the variable,
it will look at the outer reference and look for variable there (Where it looks depends where it sits Lexically)
So function b sit Lexically not inside function a so at the global level,
so it outer Environment its the Global Context
Global Execution Context -> myVar 1