Execution Context

The environment where JavaScript code is evaluated and executed.

What Is It?

The wrapper around running code that tracks everything needed for execution.

// When JavaScript runs this code, it creates an
// "execution context" — a container that holds:
//
// 1. Variable Environment (what variables exist)
// 2. Scope Chain (what outer scopes are accessible)
// 3. 'this' binding (what 'this' refers to)

const name = "Alice";
function greet() {
  console.log("Hello, " + name);
}
greet();

Execution Context =

Variable EnvironmentAll variables, functions, arguments in this scope
Scope ChainLink to parent scopes for variable lookup
this BindingWhat 'this' refers to in this context

Context Types

Three types of execution contexts in JavaScript.

1. Global Execution Context

Created when the script first runs. Only one per program.

// This runs in the Global Context:
const app = "VisualJS";
console.log(app);
// 'this' = window (browser) or globalThis

2. Function Execution Context

Created each time a function is called. Destroyed when it returns.

function add(a, b) {
  // New context created here
  const result = a + b;
  return result;
  // Context destroyed after return
}
add(2, 3); // creates context
add(5, 7); // creates another context

3. Eval Execution Context

Created inside eval(). Rarely used and generally avoided for security reasons.

Creation & Execution

Every context goes through two phases.

// Source code:
var x = 5;
function greet(name) {
  var message = "Hello " + name;
  return message;
}
var result = greet("Alice");

Before any code runs, the engine scans the entire scope. This is the Creation Phase.

1 / 3

Variable Environment

How var, let, and const are stored differently.

// In the CREATION phase:

var a = 1;    // → stored as: a = undefined
let b = 2;    // → stored in TDZ (not accessible yet)
const c = 3;  // → stored in TDZ (not accessible yet)
function d() {} // → stored as: d = <full function>

// In the EXECUTION phase:
// a = 1 (assigned)
// b = 2 (initialized, exits TDZ)
// c = 3 (initialized, exits TDZ)
DeclarationCreation PhaseBefore Init
varundefinedundefined (accessible)
letTDZReferenceError
constTDZReferenceError
functionFull definitionFully usable

this Binding

'this' is determined when the execution context is created.

// Global context:
console.log(this); // window (browser) / globalThis

// Function context (non-strict):
function show() {
  console.log(this); // window
}

// Function context (strict):
"use strict";
function show() {
  console.log(this); // undefined
}

// Method context:
const obj = {
  name: "Alice",
  greet() {
    console.log(this); // obj ← the calling object
  }
};

// Arrow functions — no own 'this':
const arrow = () => {
  console.log(this); // inherits from enclosing context
};

FAQ

Common questions about execution context.