Scope Chain
While running a line of any execution context, if it can’t find a variable, it will look at OUTER ENVIRONMENT to look for that variable, somewhere down below in the execution stack. Which outer environment to look is depend on where this function sit LEXICALLY.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function b(){ console.log(myVar); } function a(){ var myVar = 2; b(); } var myVar = 1; a(); /* it will log 1 when line 2 was executed, because function b sits in global execution context lexically, global execution context is the outer environment to function b's execution context */ |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
function a(){ function b(){ console.log(myVar); } b(); } var myVar = 1; a(); /* it will log 1 when line 4 was executed, because function b sits in function a's execution context lexically, funtion a sits in global execution context, so it look for myVar in variable enviroments in this order: b()'s variable env => a()'s variable env => global variable env */ |