When we talk about JavaScript and how it works under the hood we can't forget about Variable Environments. It's related to the Function Execution Context too.

Variable Environments

There were only simple and short definitions last. This time we will stick to it too.

Variable Environment simply means that Where variables live and how they are interrelated in memory.

function a() {
  var myVar;

function b() {
  var myVar = 2;

var myVar = 1;

We have the script. At the moment all who have read the previous parts should be aware of how and in what order the code is executed. Because of that, we will go straight to variables. Specifically, the variable myVar, which depending on the place of occurrence is 1, 2 or undefined.

In this way, the JavaScript engine handles the storage of variables in memory.

It's easy, right? As you probably figured it out on your own, every Execution Context ( Global's or Function's ) creates its own space for variables. In the next post I will talk about Scope Chain (how JavaScript is finding value of variables) of the variables but all you have to know now is that each time new Execution Context is created with its own Variable Environment.

If you want to check if this is really true, all we have to do is to run a script. When we do it, altought a variable has the same name everywhere, our result in the console will be:

Next Post

I will talk about the Scope Chain