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 the creation phase, JS will store the variables as undefined and functions code in the memory context. Also in this phase it will allocate the memory.

  • Code Execution Phase
    In the code execution phase, the JS will execute line by line. It will allocate values to the variables and will execute the functions. Functions can be treat as a mini program, it means a new Execution context will create and the memory allocation and code execution will also happen for the same.

Call stack

Call stack (Execution Stack) maintains the order of execution of of execution contexts.

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.



bino kochumol varghese profile pic

Written By

Bino Kochumol Varghese

A software engineer who is a voracious reader and an active blogger.