DEV Community

Joe Avila
Joe Avila

Posted on • Updated on

Scoping Chain

Calling a function in Javascript creates a new execution context, and when that is created so is a scope chain for that function. The scope chain defines what variables and functions this execution context has access to.

There is a global context which is the javascript file currently being executed. It's safe to assume that all execution contexts on the execution stack have access to the global context, and it's environment record. Consider the following code:

let globalVar = "this is the global context.";

function one() {
   const insideOne = "this is inside of function one.";
   globalVar = "I have access to globalVar here.";
   console.log(globalVar);

   two();

   function two() {
      const insideTwo = "this is inside of function two.";
      globalVar = "I also have access to globalVar in function two."
      console.log(insideOne, insideTwo, globalVar)
   };

};

function three() {
   const insideThree = "this is inside function three.";
   globalVar = "I also have access to globalVar in function thre.";
   console.log(insideThree, globalVar);
   console.log(insideOne);
};

one();
three();
Enter fullscreen mode Exit fullscreen mode

If you run this in your console, you'll see the messages up until we hit the last line of function three() where we try to call the variable insideOne. We don't have access to insideOne because it's outside of the current scope chain. That variable only exists in the execution context of function one() and function two(). Once those are cleared off the execution stack, javascript erases them from memory.

Notice how in our nested function we do have access to the variable insideOne, and globalVar. When an execution context creates a scope for a function it maintains the variable objects of its parent function. The global context is the parent of all functions called in a javascript file. As I mentioned earlier, we'll always have access to global variables such as globalVar. Because function two() is nested within function one() we also have access to any variables declared in function one(). Fun fact, this scoping chain is how closures are created.

You may have noticed I called two() before declaring the function. You can read about that in my Hoisting article.

Top comments (0)