JavaScript Execution Context

Dive into JavaScript execution context

October 14, 2024

An execution context is a specification device that is used to track the runtime evaluation of code by an ECMAScript implementation.

Execution Context

When a execution context has been created, whether is a global scope execution context or function scope execution context, they all have 2 phases:

At the phase of creation, two environments and a record would be created.

1. VariableEnvironment

2. LexicalEnvironment:

3. Environment Records:

Creation Phase: When JS engine executes.

  1. Create the Global Execution Context, think of this is the biggest room.
  2. In the Global Execution Context, JavaScript stores all variables and function definitions. Think of this as giving those variables and functions name tags and assigning them positions in memory.

Execution Phase: JS executes.

  1. Assign value to the variable that has been store in the Global Execution Context.
  2. Execute functions ( e.g. greeting( ) )
var greeting = "Hello";
 
function sayHello(name) {
  console.log(greeting + " " + name);
}
 
sayHello("Joe");

First JS will "read" the code from top to bottom, then creates global execution context, and this phase is called Creation Phase, in this phase, there're several tasks that need to be done.

  1. Storing variable and function definitions, think of creating two name tags, one is greeting which is a variable, another is sayHello, and it is a function.

Then we are moving forward to the second phase - Execution Phase.

  1. Assigning value of Hello to variable greeting.
  2. Executing sayHello("Joe"), this would create its own execution context, inside this execution context, it also has 2 phases like above, below is the breakdown of execution context of sayHello("Joe").

Summary

Back to Blog 🏃🏽‍♀️