DEV Community

Cover image for How Function And Variable works in JavaScript : Behind The Scenes
Md Pervez Hossain
Md Pervez Hossain

Posted on

How Function And Variable works in JavaScript : Behind The Scenes

Let's See How The Function and Variable Works in JavaScript Behind The Scenes

According to Under Code Spinate

Image description

Everything in JavaScript Happens Inside an Execution Context. All JavaScript code runs within an execution context, which provides an environment for the code execution. When JavaScript code runs, it first creates a Global Execution Context (GEC). Execution Context Does Perform by Call Stack.

What is Call Stack ?

The call stack in JavaScript is a mechanism for managing the execution context of functions. Call stack is a data structure, which follows the Last-In-First-Out (LIFO) principle. JavaScript is single-threaded, meaning it can only execute one task at a time. The call stack manages this execution flow.

Image description

It has two main components:

  • => Memory Component (Variable Environment)
  • => Code Component (Thread of Execution)

The GEC undergoes two phases:

  • => Creation Phase (Memory Creation Phase)
  • => Execution Phase (Code Execution Phase)

Image description

In the Memory Creation Phase It Allocates The Memory For a Variable And Initially set Undefined (a=undefined ). in the code execution phase it sets it's actual value ( a=10 ) then it come next line it js engine look it is a function then it allocates Memory For the Function ( Entre Full Function Code ).
function x() {
var b = 5;
var c = 20;
var result = b + c;
console.log(result);
}

Then it moves the next line and then See function is invoked ( Function call ). When a function invoked it creates Brand new Function Execution Context . and put this function in call stack at the top of GEC ( Global Execution Context )

Image description

The Brand new Function Execution Context Has ** =two Phase **:

  • => Creation Phase (Memory Creation Phase)
  • => Execution Phase (Code Execution Phase)

Image description

in the function Execution Context it allocate the memory for it's variable and set initially undefined ( b=undefined , c=undefined and, result=undefined ). then in the code execution phase it sets their Actual value and make the statement operation ( b=5 , c=20 , result=5+20) and then print console.log(25) in the browser console. after function execution Completed it *deleted and move out from the call stack and control back to the GEC of call Stack. *

Image description

After FEC ( Function Execution Context ) . then it goes the next line here is console.log (a) . In the memory creation phase it sets a=10;

Image description

After All code Execution , the GEC Moved Out From The call stack and it gets empty.

Image description

This is How The Function variable Works in JavaScript Behind the Scenes Through Call Stack.

Top comments (0)