Before jumping into start writing to code in JavaScript, you should have the understanding of how JavaScript executes code behind the scene and it can be well explained by the javascript execution context.
In this article, I am going to explain how javascript executes code with execution context. That is going to be the most fundamental topic of JavaScript, so you should make good understanding of it.
JavaScript Execution Context
JavaScript Execution Context is the area in JavaScript where the code execution happens.
Types of Execution Context
In JavaScript two different execution contexts are created.
Global Execution Context: Whenever code execution of a program starts, a Global Execution Context is created at first.
Local Execution Context: Whenever a function is called, a local execution context is created for that function.
Different Phases in Execution Context
There are two different phases of every execution context either it is global or local.
Code Phase: Code is executed line by line from top to bottom.
Memory Phase: Variables and function bodies are stored into memory.
Understanding Execution Context
Let's take an code example below to understand JS execution context:
console.log('Code execution started!');
console.log(age);
var age = 35;
console.log('Age is incremented to: ', incrementAgeByTwo(age))
function incrementAgeByTwo(age) {
var result = age + 2;
return result;
}
/**
Output:
Code execution started!
undefined
Age is incremented to: 37
*/
Step-by-step code execution of the above code:
- A global execution context is created with two different phases, a memory phase and a code phase.
- In memory phase, variables and function bodies are stored in memory.
agewith value undefined and the function body ofincrementAgeByTwo()is stored in memory.
- In code phase, the code starts executing line by line from top to bottom.
- Prints
Code execution started!in console. - Prints value of
agewhich isundefinedin console. - Value of
ageis updated to 35 - Creates local execution context of the function
incrementAgeByTwo()and prints 37, the value returned by the function in console.



Top comments (0)