🕶️
JavaScript Code Execution
Is a synchronous single threaded language
Everything runs inside Execution Context which has two components
1. Memory ⇒ Variable Environment → contains key:value pairs of variables
and functions
2. Code ⇒ Thread of Execution → where code is executed line by line
Two phases of code execution: 1. Memory creation → 2. Code Execution
Program execution starts with the creation of a Global Execution Context(GEC),
after memory allocation (phase 1), each function invocation will trigger a creation
of new Execution Context for that function and two phase execution happens for
function statements. When function’s execution context encounters return ,
control is handed back to GEC and functions execution context will be deleted.
Call Stack → Maintains the order of execution of execution contexts
Used to create / delete / maintain all the execution contexts.
GEC is the first element to be pushed onto Call Stack
Other names for Call Stack ⇒ Execution Context Stack, Program Stack,
Control Stack, Runtime Stack, Machine Stack
Scope Chain: Any Execution Context has a pointer to the lexical environment of
its immediate parent, for GEC this pointer points to null
JavaScript Code Execution 1
Hoisting is the default behaviour of moving all the declarations at the top of the
scope before code execution. Variables and functions are allotted memory during
first phase (Memory creation) of code execution hence they are accessible in the
code even before initialisation
Temporal Dead Zone is the space in memory where elements ( declared using let
and const ) are stored after hoisting but before initialization. Accessing elements
in temporal dead zone throws ReferenceError: cannot access before initialization
Block → Is a compound statement → Group of statements within { }
let and const are block scoped
JavaScript Code Execution 2