DEV Community

Cover image for How JavaScript works?
Sam
Sam

Posted on

How JavaScript works?

Let's Understand JS! There are few around the globe who loves JS like anything and the there is another part of the world who hates JS to the core. Hence on this blog, I will try to explain the behind the scenes on How JS works to make the latter part also fall in love in JS✌️😎

JS is a single threaded and synchronous language which means it can handle one task at a time.

What the heck is execution context in JS?

Image description

You can think of execution context(EC) as a container having two parts. The first part is named as Memory and also called as Variable environment and the second part is named code also called as Thread of execution .

Image description

The first being memory allocation phase, during this phase, JS skims the whole code and assigns memory to each and every variable and function; For variables during this phase, JS assigns a special placeholder called undefined and a whole copy of function code for the function.

Functions in JavaScript, when you compare with other programming languages, work differently.

Let's take an simple example,

var n = 2;

function square(num) {
 var ans = num * num;
 return ans;
}

var square2 = square(n);
var square4 = square(4);
Enter fullscreen mode Exit fullscreen mode

The above example has an function which takes an argument of type number and returns the square of the number.

Image description

The second phase is the execution phase, during which JS executes the code line by line and assigns the actual value to the variables. The functions are considered as first-class citizens in JS, they behave very differently from any other language. That being the case when JS sees a function invocation it creates a brand new execution context inside the global execution context and executes the function in the same way with this two-phase process.

Are you wondering how JS manages its job smoothly?

All these tasks of creating and deleting the EC once the work is done are managed in JS by a stack called the call stack. Call stack has also other names such as,

  • Execution Context Stack
  • Program Stack
  • Control Stack
  • Machine Stack
  • Runtime Stack
In this article, we have understood how JS works and the execution context briefly. I hope this blog is helpful, please feel free to share and comment below.

Top comments (0)