Basics of JavaScript

Neha Prabhakar
3 min readApr 11, 2024

--

Photo by Claudio Schwarz on Unsplash

JavaScript is a SYNCHRONOUS SINGLE-THREADED language.

(Explanation : JS can only execute 1 command at a time in a specific order.)

Starting with the most basic but most important concept of JavaScript i.e., Execution Context. Coming to the definition for the same in simple words, Everything inside JS happens inside an ‘Execution Context’.

EXECUTION CONTEXT:

Execution context has following 2 components :

  1. Memory also known as Variable Environment : Contains the variables and functions that are present in the code of JS.
  2. Code also known as Thread of Execution : All the code in JS is present here.

Don’t worry let’s explain it with you and example how it works.

var n = 2;
function square(num){
var ans = num * num;
return ans;
}
var square2 = square(n);
var square4 = square(4);

Here is a diagram for better understanding and the explanation for the same is mentioned in points below it.

  1. The creation of Execution context happens in 2 phases :
    a. Memory creation Phase
    b. Code execution Phase

2. Coming to the 1st phase it’s the step where memory is allocated to the variables and functions in the code as the code is read line by line. The variables are assigned a special value i.e., UNDEFINED (for now understand as placeholder special keyword in JS) whereas for functions the whole code is stored as is in the memory.

3. In 2nd phase, values are assigned to the variables as in the above mentioned example n is assigned 2 in 2nd phased.

4. While code is being gone through line by line and when it comes to line 6 where function is being invoked another execution context is created and similar steps are followed for the smaller EC.

5. As soon as return statement is encountered the EC created is deleted and control is given back to GEC and the flow continues till the program ends.

This is how the program works. Now the question arises how does JS manages so many Execution contexts?

Photo by Marcel Strauß on Unsplash

The answer to this is CALL STACK can also be called EXECUTION CONTEXT STACK or PROGRAM STACK or CONTROL STACK or RUNTIME STACK or MACHINE STACK.

So many names feel free to cal it whatever you like ;)

As soon as a GEC is created it is added to the stack and when another EC let’s say E1 from above example is created it is added over the GEC in the same stack and then when return statement executes and control is sent back to GEC the last added E1 is deleted with the flow E2 is added over GEC and when completed it gets deleted and once whole program runs the GEC is deleted too. This is how JS easily manages the Execution contexts.

Hope this was helpful and easy to understand. See you in next one! :)

--

--