Execution context

Execution context

Hello, guys! In this article, we'll learn about execution context in JavaScript

there are few concepts that will be covered along

What is an execution context

Execution basically is an environment/container in which the JavaScript code is executed. in execution context, the whole code i.e arrays, objects, functions are placed, In a proper sequence. the javascript execution happens in two Phases

  • Allocating memory for every variable and function
  • Assigning values to every variable

Different types of execution context

When I talk about execution context the first thing that comes to my mind is a container inside a container this actually sounds funny but this is what execution context is so there are different execution context for different scenarios

Global execution context

The global execution context is the parent container in which a program has every function i.e top-level functions which are directly declared are added in the global execution context.

var a = 10 ;
var b = 20 ;

image.png

here the variables are directly stored in the global execution context

Functional execution context

Functional execution context is defined as the context created by the JS engine whenever it finds any function call.

var a = 10 ;
var b = 20;
function add (){
  var z = 5 ;
   var y = 20;
}

image.png

while executing functions another execution context is created inside the global one.

after the first phase execution, these variables will be assigned a value which is given in the code now you might this If this is the case javascript creates multiple execution contexts inside contexts

to maintain this and avoid confusion javascript maintains its own execution stack which is similar to a normal stack but in this stack, the execution contexts are stored.

With all this, one more concept that comes is hoisting.

Hoisting

It is a phenomenon that occurred by accessing variables before initializing now after execution context it's very easy to understand hoisting.

We saw in the first phase the variables are assigned as undefined this is what hoisting is if we try to access a variable shown below

console.log(a) // undefined
var a = 10

this code won't generate an error instead it will give output as undefined because in the first phase the console.log is executed but var a is defined as undefined in the execution context.

These are some basic topics that are covered in this blog, Stay tuned I will be posting more advanced topics soon :)