Ticker

6/recent/ticker-posts

Chapter 8: Execution Context — What Actually Happens When JS Runs Your Code

 

Chapter 8: Execution Context — What Actually Happens When JS Runs Your Code

The Biggest Mistake Most JavaScript Beginners Make

When beginners write code, they usually think something like this:

let name = "Aqad";

function greet() {
console.log("Hello " + name);
}

greet();

And then they assume:

JavaScript reads line 1
JavaScript reads line 2
JavaScript reads line 3
JavaScript reads line 4
Done

This is partially true.

But something much more interesting is happening behind the scenes.

In reality, before JavaScript executes your code, it performs preparation work.

Think of it like preparing a restaurant before customers arrive.

Before the first customer orders food:

  • Tables are arranged
  • Ingredients are prepared
  • Staff members arrive
  • Cash counter is opened
  • Kitchen is cleaned

Only after preparation is complete does the restaurant begin serving customers.

JavaScript behaves in a similar way.

Before executing your code, JavaScript prepares an environment.

This environment is called:

Execution Context

Understanding Execution Context is one of the most important milestones in becoming a professional JavaScript developer.

Because many advanced concepts depend on it:

  • Hoisting
  • Scope
  • Closures
  • Call Stack
  • Event Loop

If Execution Context becomes clear, the next several chapters become much easier.


What Is Execution Context?

Execution Context is the environment in which JavaScript code runs.

It contains everything JavaScript needs to execute your program.

Think of it as a workspace.

Before work starts, JavaScript creates a workspace containing:

Memory
Variables
Functions
References
Execution Information

Only after this workspace is ready does JavaScript start running code.


Real Life Office Analogy

Imagine a company hires a new employee.

Before work begins:

Desk Assigned
Laptop Assigned
Employee ID Created
Email Created
System Access Granted

Only then can the employee start working.

Execution Context works similarly.

JavaScript prepares everything first.

Then execution begins.


Every JavaScript Program Creates an Execution Context

Consider:  console.log("Hello World");

Looks tiny.

But JavaScript still creates an execution context before running it.

Even the smallest JavaScript program cannot run without one.


Types of Execution Context

There are mainly three types.

Global Execution Context

Created when the application starts.

Function Execution Context

Created whenever a function runs.

Eval Execution Context

Created by the eval() function.

In modern development, developers rarely use eval().

Therefore, we mainly focus on:

  • Global Execution Context
  • Function Execution Context

Understanding Global Execution Context

Imagine opening a new JavaScript file.

let company = "AQAD";

function welcome() {
console.log("Welcome");
}

As soon as JavaScript starts reading this file:

A Global Execution Context is created.

Think of it as the main headquarters of your application.

Everything starts here.


What Happens Inside Global Execution Context?

JavaScript does not immediately execute code.

Instead it performs two phases.

These phases are extremely important.

Phase 1

Memory Creation Phase

Phase 2

Execution Phase

Most beginner confusion disappears once these two phases become clear.


Phase 1: Memory Creation Phase

Before execution begins:

JavaScript scans the entire code.

It identifies:

  • Variables
  • Functions

Memory is allocated for them.

Consider:

var user = "Aqad";

function greet() {
console.log("Hello");
}

During Memory Creation Phase:

JavaScript stores:

user  → undefined

greet → complete function definition

Notice something interesting.

The variable does not receive its value yet.

Instead:

user → undefined

This behavior becomes very important when we study Hoisting.


Visualizing Memory Creation

Code:

var user = "Aqad";

function greet() {
console.log("Hello");
}

Memory: 

Memory Space

user → undefined

greet → function() {
console.log("Hello");
}

Nothing has executed yet.

JavaScript is only preparing.


Phase 2: Execution Phase

After memory preparation completes:

JavaScript starts executing code line by line.

Code:

var user = "Aqad";

Updates memory:

user → Aqad

Function declaration:

function greet() {}

already exists in memory.

No further action needed.

Execution phase continues.


A Complete Example

Code:

var x = 10;

function square(num) {
return num * num;
}

var result = square(x);

Let's see what JavaScript does.


Step 1: Memory Creation Phase

Memory becomes:

x → undefined

square → function definition

result → undefined

Step 2: Execution Phase

Line 1:  x = 10

Memory: x → 10

Line 2: Function already stored.

Nothing changes.

Line 3: result = square(x)

Function is called.

Something new happens.

JavaScript creates another Execution Context.


Function Execution Context

Whenever a function runs:

JavaScript creates a brand-new execution context.

Think of it like a temporary office room.

Example:

function greet() {
console.log("Hello");
}

greet();

When: greet();  runs,

JavaScript creates:

Function Execution Context

This context exists only while the function executes.

After completion:

It gets destroyed.


Restaurant Analogy for Function Context

Imagine a restaurant.

Main restaurant:

Global Execution Context

Customer places an order.

Kitchen starts preparing food.

Temporary workspace:

Function Execution Context

Once food is delivered:

Workspace disappears.

Similarly:

Function Runs

Context Created

Work Completed

Context Removed

Example with Function Context

function multiply(a, b) {
return a * b;
}

multiply(5, 4);

Function call creates:

Function Execution Context

a → 5
b → 4

Execution:   5 * 4

Result:  20

Function completes.

Context removed.


Every Function Gets Its Own Context

Example:

function one() {
console.log("One");
}

function two() {
console.log("Two");
}

one();
two();

JavaScript creates:

Global Context



Function Context One



Destroyed



Function Context Two



Destroyed

Each function gets its own workspace.


Variables Live Inside Their Context

Example:

function test() {

let secret = "Hidden";

console.log(secret);
}

test();

Inside function:

secret = Hidden

Outside function:

console.log(secret);

Output:

ReferenceError

Why?

Because:

secret

belongs to the function's execution context.

Once the function finishes, that context disappears.


Visualizing Execution Context Structure

A simplified execution context contains:

Execution Context

├── Memory Component

└── Code Component

Memory Component stores:

Variables
Functions
References

Code Component executes:

Line-by-Line Instructions

Think of it as:

Office

Cabinets → Memory

Employees → Executing Code

Why Execution Context Matters

Many confusing JavaScript behaviors become clear once you understand execution context.

Example:

console.log(a);

var a = 10;

Many beginners expect:

ReferenceError

But output is:

undefined

Why?

Because during memory creation:

a → undefined

already exists.

We'll explore this in detail in the Hoisting chapter.


Execution Context and Real Applications

Every application you use relies on execution contexts.

Examples:

Banking App

transferMoney()

creates a function context.


Login System

loginUser()

creates a function context.


E-Commerce

placeOrder()

creates a function context.


Food Delivery

calculateDeliveryCharge()

creates a function context.

Every user action usually triggers one or more new execution contexts.


Common Beginner Misconceptions

Misconception 1

"JavaScript immediately executes code."

Reality:

Memory Creation

Execution

Misconception 2

"Functions run inside the global context."

Reality:

Each function gets its own execution context.


Misconception 3

"Variables appear only when JavaScript reaches them."

Reality:

Variables are registered during memory creation.


A Mini Visualization of Everything Together

Code:

var company = "AQAD";

function greet() {
var message = "Welcome";
console.log(message);
}

greet();

Memory Creation:

company → undefined

greet → function definition

Execution:  company → AQAD

Function Call: 

Create Function Context

message → undefined

Execution:

message → Welcome

Print:

Welcome

Function Ends:

Function Context Destroyed

Global Context Continues.


Why Senior Developers Care About Execution Context

Most interview questions around:

  • Hoisting
  • Scope
  • Closures
  • Call Stack
  • Event Loop

are actually testing your understanding of Execution Context.

If you master this chapter, you already understand the foundation beneath several advanced JavaScript concepts.

This is where many developers transition from writing JavaScript to truly understanding JavaScript.



Post a Comment

0 Comments