Execution Context & Call Stack in JavaScript

Sameer Supe
3 min readAug 14, 2021

Everything in JavaScript happens within an Execution Context. When a function runs in JavaScript execution context is created. Let’s take an example.

Example

In the above example, JS interpreter goes through entire program and creates an Execution Context. There are two phases in Execution Context. First is Memory Allocation and Second is Code Execution.

Memory Allocation

In first phase all variables and functions are allocated memory. All variables (a, sqFirst, sqSecond) in the given example will be allocated memory and initialized as undefined. The functions will be assigned with their code, as an initial value

Memory Allocation in Scope

Code Execution

After the first phase of memory allocation, in next phase our code will be executed. Starting from the first line again, first key variable will be assigned the given value of 3. After that, in the next step, since function square has no values, it will be skipped. On the next line there is a function invocation. Whenever a new function is invoked, a new execution context is created. Now we will again go through two phases of execution context, Memory allocation and Code execution. In the first phase, all variables and functions will be allocated some memory. In function square, parameter num and variable ans will be initialized as undefined. In second phase, num will assigned value of sqFirst argument, i.e. 3. and ans will be assigned value of 9 after performing the operation. On next line return keyword will force the execution control back to the sqFirst, from where function invocation happened and it value of sqFirst will be updated to 9. Afterwards sqSecond will also go through same process, however instead of n it has an argument of 5 so, the value will be 25.

Values assigned to given arguments after Code Execution

Call Stack

As you can see (read), this is a very tedious process to manage. There can be any number contexts within a context, so this execution control is managed within a stack by Call Stack. Call stack manages all execution contexts for us, whenever a context is created, it is pushed into this stack & after completion it is popped off the stack. It is basically a to-do list of all arguments

Reference:

--

--