Scope Chain

At the beginning I would like to talk about a similar case as we had in the last part.

Look at the script above. The difference between this and the one from the previous part is that in the first function (function a) we do not declare a variable. The only thing we want to do there is to console.log a variable myVar.

We have four options.

  1. not definied
  2. undefined
  3. 1
  4. 2

Can anyone know which one will be correct and why? If not, scroll down a little bit. 

 

 

 

 

 

 

 

 

 

 

Welcome back!

The correct answer is:

Now I will try to explain why.

Let's start with whether or not you remember from the first part what the Lexical Environment is? In short it means that it is important Where the code is located.
Thus, function a, function b and initialization of the variable myVar lexically are in the same Lexical Environment, and Global Environment.
The fact that the function a is invoked in the function b, in no way affects the environment in which it was created.
The initialization of variables has the same rules. From the perspective of the JavaScripy engine, initializing the variable myVar in function b is not visible to the function because both sit lexically on the same, global level.

From previous parts you should remember that when Execution Context is created, we also get a reference to Outer Environment.
As we have already agreed that both functions and initialization of myVar = 1 are on the same level, we can easily guess that for the Execution Context of the function a, Outer Environment will be the Global Environment.
And it is there, and not in function b, the JavaScript engine will search for the variable myVar if it does not find it in the function a.

The function b is exactly in the same situation as function a. If the JavaScript engine did not find the myVar variable there, it would look in its Outer Environment.
It should also be remembered that it is not important whether the function a is before or after the function b. Both sit lexically in the same Global Environment.

This is what we call the Scope Chain.

Finally, let's take a look at another, similar case.

In the script above, we put the function a into the function b. Thanks to this, we have changed the Lexical Environment of function a. As you can easily see both functions are no longer on the same level.
So even though the Outer Environment of function b will still be the Global Environment, that's not the case for function a anymore. Because of that, console.log this time will not be 1 but 2.

Feel free to play with a variable and many functions to get familiar with how it works.

Next Post

We will leave for a while Execution Context and related to it topics and talk about types and operators in JavaScript.