How JS code is executed.

JavaScript is a synchronus (moves to the next line only when the execution of the current line is completed) and single-threaded (can execute one command at a time in specific order) language.

Execution Context

Whenever a JS files executes, JavaScript engine will creates a default Execution Context know as Global Execution Context. Everything in JavaScript happens inside an Execution Context. You can treat its as a container where the whole process is going to happen.

Execution context have two componets as below and JavaScript code gets executed in two phases.

  • Memory Component or Variable Environment
  • Code Component or Thread of Execution

Inside the Execution Contexts

Two phases after creating Execution context as below,

  • Memory Allocation phase (Creation phase)
    In this phase, all the variables and functions get their memory allocated in the memory with undefined and the entire code respectively.

  • Code Execution Phase
    In this phase thread execution happens and all the variables get their actual values which were assigned to them and as function is invoked, a new execution environment gets created in the code part, and again there are two phases, memory allocation phase and code execution phase. And the cycle repeats.

Call stack

Call stack (Execution Stack) maintains the order of execution of of execution contexts and it is a stack with LIFO (Last in, first out) structure in which items can only be added or removed from the top of the stack only.

Whenever a JS program is run, the call stack is populated with this Global execution context. When a function is invoked a new execution pushed to the stack and after the function execution it will popped out of the stack and the control reaches to the execution context below it in the stack.

References

GeeksforGeeks
freeCodeCamp
YT Namastae JavaScript


Read More