DEV Community

Belal Ahamed
Belal Ahamed

Posted on

JS Internals : JavaScript Execution Context

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.

  1. Global Execution Context: Whenever code execution of a program starts, a Global Execution Context is created at first.

  2. 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.

  1. Code Phase: Code is executed line by line from top to bottom.

  2. 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
*/
Enter fullscreen mode Exit fullscreen mode

Step-by-step code execution of the above code:

  1. 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. age with value undefined and the function body of incrementAgeByTwo() 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 age which is undefined in console.
  • Value of age is 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)