DEV Community

Sai Swaroop Bijinapalli
Sai Swaroop Bijinapalli

Posted on

JavaScript Fundamentals

🚀 JavaScript Fundamentals (Week-03): Understanding Execution Context, Scope & Closures

"When I started learning JavaScript, I could write functions and variables, but I didn't understand what actually happened behind the scenes. Questions like 'Why can an inner function access an outer variable?' or 'Why does JavaScript remember a variable even after a function finishes?' made me curious. This week, I explored three important concepts that answer these questions: Execution Context, Scope, and Closures."


📖 Introduction

JavaScript is more than just writing variables and functions. Every time we run a JavaScript program, the JavaScript engine creates an environment to execute our code.

Understanding how JavaScript manages variables, functions, and memory is essential before moving on to advanced topics like asynchronous programming, React, or Node.js.

In this article, we'll explore:

  • What is Execution Context?
  • How JavaScript executes code
  • What is Scope?
  • Types of Scope
  • What is a Closure?
  • Why Closures are useful

📌 What is Execution Context?

Before JavaScript executes any code, it creates a special environment called the Execution Context.

Think of it as JavaScript's workspace.

This workspace contains everything needed to execute the program:

  • Variables
  • Functions
  • The value of this
  • Scope information

Without an Execution Context, JavaScript wouldn't know where variables or functions exist.


Types of Execution Context

JavaScript creates two main execution contexts.

1️⃣ Global Execution Context (GEC)

This is created when the program starts.

There is only one Global Execution Context for each JavaScript program.

Example:

let name = "Sai";

console.log(name);
Enter fullscreen mode Exit fullscreen mode

Before executing this code, JavaScript creates the Global Execution Context.


2️⃣ Function Execution Context (FEC)

Whenever a function is called, JavaScript creates a new Execution Context for that function.

Example

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

greet();
Enter fullscreen mode Exit fullscreen mode

When greet() runs, JavaScript creates a Function Execution Context.

Once the function finishes, its execution context is removed from memory.


How Does Execution Context Work?

Every Execution Context has two phases.

Phase 1: Memory Creation Phase

Before executing the code, JavaScript scans the program.

During this phase:

  • Memory is allocated for variables.
  • Function declarations are stored.
  • var variables are initialized with undefined.
  • let and const are hoisted but remain in the Temporal Dead Zone (TDZ) until initialized.

Example

console.log(a);

var a = 10;
Enter fullscreen mode Exit fullscreen mode

Memory created:

a = undefined
Enter fullscreen mode Exit fullscreen mode

Phase 2: Execution Phase

Now JavaScript executes the code line by line.

Variables receive their actual values, and functions are executed.

var a = 10;

console.log(a);
Enter fullscreen mode Exit fullscreen mode

Output

10
Enter fullscreen mode Exit fullscreen mode

Execution Context Flow

Program Starts

        │

        ▼

Global Execution Context

        │

        ▼

Memory Creation Phase

        │

        ▼

Execution Phase

        │

        ▼

Function Call

        │

        ▼

Function Execution Context

        │

        ▼

Memory Phase

        │

        ▼

Execution Phase

        │

        ▼

Function Ends

        │

        ▼

Back to Global Context
Enter fullscreen mode Exit fullscreen mode

🌍 What is Scope?

Have you ever wondered why some variables can be accessed everywhere while others cause an error?

That's because of Scope.

Definition

Scope is the area where a variable is accessible.

Simply put,

Scope decides where we can use a variable.


Why is Scope Important?

Without Scope, every variable would be accessible everywhere.

This would cause:

  • Variable conflicts
  • Difficult debugging
  • Security issues
  • Poor code organization

Scope solves these problems by limiting where variables can be accessed.


Types of Scope

Global Scope

Variables declared outside all functions belong to the Global Scope.

let company = "OpenAI";

function showCompany() {
    console.log(company);
}

showCompany();
Enter fullscreen mode Exit fullscreen mode

Output

OpenAI
Enter fullscreen mode Exit fullscreen mode

The variable company is accessible everywhere.


Function Scope

Variables declared inside a function are available only inside that function.

function student() {

    var name = "Sai";

    console.log(name);

}

student();
Enter fullscreen mode Exit fullscreen mode

Output

Sai
Enter fullscreen mode Exit fullscreen mode

Trying to access name outside the function will produce:

ReferenceError
Enter fullscreen mode Exit fullscreen mode

Block Scope

Variables declared with let or const exist only inside the block {}.

{
    let city = "Hyderabad";
    console.log(city);
}
Enter fullscreen mode Exit fullscreen mode

Output

Hyderabad
Enter fullscreen mode Exit fullscreen mode

Outside the block:

console.log(city);
Enter fullscreen mode Exit fullscreen mode

Output

ReferenceError
Enter fullscreen mode Exit fullscreen mode

Lexical Scope

Lexical Scope means an inner function can access variables declared in its outer function.

function outer() {

    let message = "Hello";

    function inner() {

        console.log(message);

    }

    inner();

}

outer();
Enter fullscreen mode Exit fullscreen mode

Output

Hello
Enter fullscreen mode Exit fullscreen mode

This happens because JavaScript remembers where the function was created.


🔗 Scope Chain

When JavaScript cannot find a variable in the current scope, it searches the parent scope.

Current Scope

↓

Parent Scope

↓

Global Scope

↓

ReferenceError
Enter fullscreen mode Exit fullscreen mode

This process is called the Scope Chain.


🔒 What is a Closure?

Closures are one of the most powerful features of JavaScript.

Definition

A Closure is a function that remembers variables from its outer function even after the outer function has finished executing.

In simple words,

A Closure allows an inner function to continue using variables from its parent function.


Why are Closures Needed?

Normally, local variables disappear after a function finishes.

Closures allow those variables to stay alive as long as another function still needs them.

This is useful for:

  • Data privacy
  • Counters
  • Event handlers
  • Module patterns
  • Maintaining state

Closure Example

function counter() {

    let count = 0;

    return function () {

        count++;

        console.log(count);

    };

}

const increment = counter();

increment();
increment();
increment();
Enter fullscreen mode Exit fullscreen mode

Output

1
2
3
Enter fullscreen mode Exit fullscreen mode

How Does This Work?

When counter() is called:

  • JavaScript creates count.
  • It returns the inner function.
  • Even after counter() finishes, the inner function still remembers count.

Every time increment() is called:

  • count increases by one.
  • The value is preserved because of the Closure.

Key Takeaways

✔ JavaScript creates an Execution Context before executing code.

✔ Every Execution Context has a Memory Creation Phase and an Execution Phase.

✔ Scope determines where variables can be accessed.

✔ JavaScript supports Global Scope, Function Scope, Block Scope, and Lexical Scope.

✔ Closures allow functions to remember variables from their outer scope.

✔ Closures are commonly used for data privacy, counters, and maintaining state.


Conclusion

Understanding Execution Context, Scope, and Closures changed the way I think about JavaScript. These concepts explain what happens behind the scenes whenever our code runs. Once you understand them, advanced topics like asynchronous programming, callbacks, Promises, React Hooks, and Node.js become much easier to learn.

I hope this article helped you build a stronger JavaScript foundation. If you're learning JavaScript too, feel free to share your thoughts or ask questions in the comments.

Top comments (0)