Skip to main content

Command Palette

Search for a command to run...

How Javascript works?

Execution context, Callstack

Updated
2 min read
How Javascript works?
A

I am frontend developer from India.

In this article, we will discuss execution context and callstack. We will also see how the script gets executed step by step.

start

In Javascript, Execution Context is defined as an environment where the code gets executed.

One can simply think of execution context as a box where all execution takes place.

The execution context is divided into two parts:

1. Memory(Variable environment)-It consists of all key-value pairs of variables, constants, functions.

2. code(Thread of execution) -Place where code is executed one line at a time.

intro

Javascript is synchronous,single-threaded language.

In simple words, it means that only one line of code is executed at a time and the code executes in a specific order the next line of code is executed only when the current line has finished its execution.

Understanding execution in javascript through a code sample

var x = 10;

function timesfive(a){
   num=a*5;
    return num;
}

 var y = timesfive(x);

Now let us see how this code gets executed behind the scenes

  • When this code is run a global execution context is created.

Screenshot from 2021-06-08 18-02-52.png

  • The execution now happens in two phases namely:

    1. Creation Phrase(Memory Allocation Phrase):In this phrase javascript allocates memory to all variables, constants and functions. In this phrase, it stores the initial value of variables as undefined. In the case of functions whole code is stored inside the allocation phrase.

Screenshot from 2021-06-08 18-13-09.png

2. Code execution phrase:In this phrase the code is executed line by line. The value is assigned to variables and functions calls are executed.

Screenshot from 2021-06-08 18-52-48.png

Now, for every function call, the javascript engine creates a function execution context.

Screenshot from 2021-06-08 19-02-09.png

Now the num value is calculated

Screenshot from 2021-06-08 19-06-41.png

Screenshot from 2021-06-08 19-07-45.png

After the value is calculated the control returns back to the global execution context.

Screenshot from 2021-06-08 19-15-25.png

Screenshot from 2021-06-08 19-18-00.png

Now the whole code is executed the global execution context is deleted.

CallStack

Callstack is a stack in a javascript engine to keep track of all the function calls. The global execution context is at the bottom of the stack. Once the function is executed it is popped out from the stack.

Screenshot from 2021-06-08 19-28-15.png

That's all for this article. Thanks a lot.

Thanks

More from this blog

A

Aakanksha Dhurandhar's Blog

14 posts