⏱ 0:07est. 5 min
Chapter 16- The Scope Chain
Notes
Example 1
function b(){
console.log(myVar);
}
function a(){
var myVar = 2;
b();
}
var myVar = 1;
a();
Output
1
Explanation
- First of all global execution context is pushed on stack with myVar =1
- Then a() gets executed and it's execution context is created and executed myVar =2 and it's pushed on stack
- Then b() gets executed with its execution context. There is no myVar in its execution context environment. Each execution context has its own variable object "this"
- Every execution context has reference to its outer environment. In the case of function b() it's outer environment is the global execution context and that's also the case in function a() even though a() is exactly below b() in execution stack as far as what code is going to run
- Lexical environment - Where something is written physically in your code is important.
- b() lexically sits on top of the global environment. If js can't find variable in current execution context it looks at the outer reference and go looks for variable there somewhere down below it in the execution stack and the outer environment where it points is going to depend on where the function sits lexically. So it's outer environment is global execution context
- This chain of references to outer environment is called Scope Chain. Scope means where i can access the variable and chain is links of outer env.
- We can change this by changing the lexical environment of the function. b() is lexically in global environment.
-----------------------------------------------------------------------------------------------
Example 2
function a(){
var myVar = 2;
function b(){
console.log(myVar);
}
b();
}
var myVar = 1;
a();
Output
2
Explanation
- Here we have changed the lexical environment of b() now the outer reference of b() would be execution context of a() because b() is physically sitting inside function a()
------------------------------------------------------------------------------------------
Example 3
function a(){
function b(){
console.log(myVar);
}
b();
}
var myVar = 1;
a();
Output
1
Explanation
- Now lexical outer environment of function b() is a() and as myVar is not defined in a() it will check declaration of myVar in its global outer environment.