Table of contents
No headings in the article.
Execution Context
is the cerebrum🧠 of JS language.
To understand this, firstly we need to conclude JS
run-time
in a bigger picture 🖼️
NOTE: JavaScript mechanism is broadly divided into 2 phases.
✍️
Execution Context is JS
run time
. This simply means during dynamic or execution time how JS engine behaves.By default, there is always a
Global Execution Context
whenever we write any JS program.Function creates its own
Execution Context
.If there is no function in our program then only
Global Execution Context
exists.We can also say
EC
is like a container and within that, we get all the global objects.To have a better understanding let's understand through code snippets.
let name = 'JS'
function myFunc(msg){
return console.log(`${name} is the best programming language!`);
}
myFunc(name);
Firstly, let's understand the above code through a diagram
Execution Context in JS
- Firstly
compilation/ memory creation phase
will start within which all the declaration & memory space allotment will take place.
compilation phase also known as memory creation phase
In this phase, JS skims through the entire program & allocates memory to the variables & functions.
As soon as it gets the variable it assigns the
special
value to it ->undefined
.name variable and func method will be declared in the global scope
undefined
value will be assigned to name variables.And the
entire code
of the myFunc function will be assigned tomyFunc
method.
NOTE: The time when the variable is declared with either let or const but no value is assigned other than undefined & can't be accessed. Therefore, this zone is known as temporal dead zone.
Runtime/Code Execution phase :
During this phase
utilization of memory
,assignment
, andprogram execution
takes place.Values get assigned to the placeholder (variable) in this phase.
Function invocation creates a new
execution context (brand new one)
. And again all thememory creation
andcode execution
phase happens for that particular function.JS
value will be assigned to a variablename
. In the last line of our programfunction invocation
is happening. Since, function invocation creates a newexecution context
. again all thememory creation
andcode execution
phase happens for myFunc function.Now, control will go to
myFunc
function and the value ofJS
will be passed to thename
argument & it will be collected by the parametermsg
.return
keyword will pass the control of the program to the last line of the program where function invocation takes place with the value passed in theconsole.log
.Once the control goes away from the function. The
Execution Context
of myFunc function will be ended.Once our entire program is skimmed
the global execution context
also ends.