DEV Community

Tanishq Kr. Kaushal
Tanishq Kr. Kaushal

Posted on

What the hell is this Execution Context?!

JavaScript has quite the reputation for being the most popular language in the world, and 98% of world's websites use JavaScript as their main source of development for either front, end or both ends.

But how does JS functions under the hood to be this popular and powerful?

It is all possible because of the JavaScript runtime environment, which contains many functionalities and tools which contains the call stack, the event loop, callback queue, microtask queue, a collection of web APIs. More on that JS runtime env.

Inside the call stack, the code is executed one function at a time. Every time code is executed an Execution context is created with it.

An execution context is a virtual environment which includes 2 parts, the variable environment (memory) & Thread of execution (Code)

Variable Environment:

The values inside the this are stored as key:value pairs registering all the variables and functions inside the code. The variables are stored as the variable itself, and same with the functions, it stores functions as a whole no matter the size, there are indeed certain exceptions, but overall functions are stored as whole inside the Execution context as a whole.

Thread of Execution:

Inside this all the functioning happens, the code is executed line by line, since JS is a single threaded language, it can only execute one command of line at once.

Here's my poorly drawn adaptation of an Execution context:
Execution context

The process:

JS skims through the code twice, in the first run, it registers all the variables and functions. Functions are registered as they are, but in case of variables, they are stored as 'undefined'. It means we can access the variable prior to it being defined but it'll return undefined.

for ex:

console.log(a);
var a = 10;
Enter fullscreen mode Exit fullscreen mode

This is a valid code in JS it'll log undefined in the console, but do take note this is only possible in ONLY the case of var and not let/const. That's one of the differences between var, let and const. This phenomenon to access variables prior to their declaration is hoisting, more on that in another blog.

On the second run it executes the code line by line and every time there is a variable is defined, it updates the value of that variable from undefined to the value inside the variable environment.

Once the execution is completed, the Execution context is popped off the call stack.
At the base, every time the code is run, the Global Execution context is created, and every Execution context after that is on top of it.

And that is how the code is executed inside the JS runtime, but this is only the tip of the iceberg, there are a LOT of tools inside the JS Runtime that plays a role in executing code!

Hope you liked! :)

Top comments (0)