DEV Community

Cover image for Javascript Working Mechanism
ikbal arslan
ikbal arslan

Posted on

Javascript Working Mechanism

when the javascript engine starts executing the code it does :

  • executing code line by line
  • store the data after executing

and it knows the order of executions via call stack. at the bottom of the call stack, there is always a global execution context that will stay.

Running the code is also known as Execution Context

as an example let's analyze this code

Image description

while executing this code by order:

- in the memory create a variable and name it a after that set 12 as the value.
- in the memory create a variable and name it square after that set a function definition as a value
- in the memory create a variable and name it sum after that set a function definition as a value
- call the sum 
     - push sum on top of the call stack
     - get the function definition from the global memory
     - create a brand new execution context for sum.
Enter fullscreen mode Exit fullscreen mode

Image description

 - create a local memory for the execution context
 - create a variable in the local memory and name it twoSquare until finding the value set null as a value
 - call the square function:
     - push the square function on top of the call stack
     - get the function definition from global memory
     - create a new execution context for square
Enter fullscreen mode Exit fullscreen mode

Image description

     - return the value 4 as a result of the function and set it to the twoSquare value 
     - remove(pop) the square function from the call stack
     - The square execution context will be destroyed by the garbage collector.
Enter fullscreen mode Exit fullscreen mode

Image description


- get the value of the variable a from the global variable 
- calculate the execution context and return the value 16 as a result of the function 
- remove the function sum from the call stack 
- garbage collector will destroy the execution context for function sum

Enter fullscreen mode Exit fullscreen mode

Image description

- then console log hello
- end the global execution context
Enter fullscreen mode Exit fullscreen mode

Top comments (0)