DEV Community

Cover image for Javascript Working Mechanism
ikbal arslan
ikbal arslan

Posted on

2

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

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs