Hello! Welcome to the first lesson in our new module.
In our previous module, we mastered functions, learning how to define them, pass arguments, return values, and even set default parameters. We treated them as building blocks for our programs. Now, we're going to peek behind the curtain to understand one of the most fundamental concepts in JavaScript: scope.
This lesson kicks off our deep dive into how JavaScript's engine truly works. Today, we'll explore how scope defines the "visibility" or "accessibility" of your variables. Understanding this is not just academic; it's essential for writing bug-free, predictable code and is a cornerstone for mastering advanced concepts in TypeScript and Next.js.
By the end of this lesson, you will be able to explain global, function, and block scope and understand how they determine where you can and cannot use your variables.
What is Scope?
Imagine your program is a large building. Scope is like the system of rooms, floors, and security keycards in that building. It defines where a variable "lives" and who has permission to access it.
- Some variables are in the main lobby (Global Scope), accessible to anyone on any floor.
- Some are in a specific office (Function Scope), only accessible to people inside that office.
- Some are in a small, temporary meeting cubicle (Block Scope), accessible only to those in that cubicle for a short time.
Without these rules, anyone could walk into any office and change important documents, leading to chaos. In programming, this "chaos" manifests as bugs that are difficult to track down.
Consider this simple example:
function sayHello() {
const message = "Hello, world!";
console.log(message); // This works fine!
}
sayHello(); // Prints "Hello, world!"
// Now, let's try to access 'message' from outside the function
console.log(message); // ✗ This will cause an error!
Running this code will result in a ReferenceError: message is not defined. Why? Because the message variable lives inside the sayHello function's scope. Once the function finishes running, its "room" is locked, and the message variable is no longer accessible from the outside.
The "Why": Execution Context and Scope
You asked for the deep theory, and this is where it begins. The reason scope exists is because of how the JavaScript engine runs your code. For every piece of code that runs, the engine creates an Execution Context—an environment that contains everything needed to execute that code.
- Global Execution Context: Created when your script first starts. It's the base level of your program.
- Function Execution Context: A new one is created every time a function is called.
Each execution context has its own private memory for variables. This is the "under the hood" reason why the message variable from our example wasn't available globally. It belonged exclusively to the execution context of the sayHello function.
Let's watch a video that visualizes this process perfectly.
Master JavaScript Execution Context — Hoisting, Scope & Closures Made Clear
The video 'Master JavaScript Execution Context' provides a clear, step-by-step visualization of how a function's execution context is created and then destroyed, making it clear why its internal variables are not accessible from the outside.
Please watch from 00:39:27 to 00:42:25. This segment directly addresses the concept of scope by showing: A global execution context being created. A new function execution context being created when a function is called. A variable (message) being created inside the function's context. The function context being destroyed after it finishes. The final ReferenceError when the global context tries to access the message variable.
This animation of creation and destruction is the core reason scope works the way it does. The parent (global) scope cannot access things that belong to the child (function) scope because, by the time the parent gets control back, the child's scope has often been completely removed.
The "How": Lexical Scope and the Scope Chain
So, if a function can't find a variable in its own "room," how does it access variables from the outside, like global ones? This is possible thanks to two concepts: Lexical Scope and the Scope Chain.
- Lexical Scope (or Static Scope): This means that the accessibility of variables is determined simply by where you write them in your code. An inner function is lexically inside an outer function.
- The Scope Chain: When JavaScript needs to find a variable, it starts by looking in the current execution context's scope.
- If it finds it, great!
- If not, it looks at the outer scope (the "parent" scope where the function was defined).
- It continues this process, moving from the inside out, until it either finds the variable or reaches the global scope. If it still can't find it, you get a
ReferenceError.
This process is like looking for your keys. You first check your pocket (local scope). If they're not there, you check the room you're in (outer scope). If not, you check the whole house (global scope). You can always look outwards, but someone in the living room can't check your pocket.
⚡️⛓JavaScript Visualized: Scope (Chain)
Lydia Hallie's article 'JavaScript Visualized: Scope (Chain)' has some excellent, simple diagrams that illustrate this outward search process.
Read the first two sections of the article, from the beginning down to the 'waterfall' diagram. Focus on how the engine finds the city variable by 'going down the scope chain' to the outer, global scope. Also, note the key rule: you can go to outer scopes, but not to inner scopes.
The Three Types of Scope
Now that we understand the theory, let's look at the three specific types of scope you will use every day. This is where the choice between var, let, and const becomes crucial.

Scope & Closures - 33 JavaScript Concepts
The article 'Scope & Closures' from 33 JavaScript Concepts gives a fantastic and detailed breakdown of each scope type, along with the behaviors of var, let, and const.
Please read the sections titled 'The Three Types of Scope' and 'var vs let vs const'. This is the most important part of the lesson. Pay close attention to: Global Scope: What it is and why 'global pollution' is bad. Function Scope: How it is tied specifically to the var keyword. Block Scope: How let and const are scoped to curly braces {} (like if statements or loops).
Let's summarize the key points from that reading:
1. Global Scope
Variables declared outside of any function or {} block are in the global scope.
const appName = "MyCoolApp"; // Global variable
function showAppName() {
console.log(appName); // Accessible here
}
if (true) {
console.log(appName); // And also accessible here
}
Best Practice: Avoid creating lots of global variables. They can be accidentally changed by any part of your code, leading to unpredictable behavior.
2. Function Scope
Variables declared with var are function-scoped. They are only accessible within the function they are created in, regardless of any {} blocks.
function calculate() {
var total = 100; // Function-scoped
if (total > 50) {
var message = "You get a discount!"; // STILL function-scoped!
console.log(message); // "You get a discount!"
}
console.log(message); // "You get a discount!" (Accessible outside the if-block)
}
calculate();
// console.log(total); // ReferenceError: total is not defined
The behavior of message here is a classic source of bugs in older JavaScript code.
3. Block Scope
This is the modern standard. Variables declared with let and const are block-scoped. They are only accessible within the nearest enclosing curly braces ({}).
function calculateModern() {
let total = 100; // Block-scoped to the function
if (total > 50) {
let message = "You get a discount!"; // Block-scoped to the if-statement
console.log(message); // "You get a discount!"
}
// console.log(message); // ReferenceError: message is not defined!
}
calculateModern();
Because message was declared with let, its life is confined to the {} of the if statement. This is much more predictable and is why you should always prefer let and const over var.
Test your understanding!
Take a look at the following code. Without running it, what do you think will be logged to the console for console.log(a), console.log(b), and console.log(c)? Explain why for each.
const a = "I am global";
function myScopeTest() {
var b = "I am function-scoped";
if (true) {
let c = "I am block-scoped";
console.log(a); // What prints here?
console.log(b); // What prints here?
}
console.log(c); // What prints here?
}
myScopeTest();
Show answer
console.log(a)will print "I am global". The engine looks forainside theifblock, doesn't find it. It looks in themyScopeTestfunction, doesn't find it. It looks in the global scope and finds it.console.log(b)will print "I am function-scoped". The engine looks forbinside theifblock, doesn't find it. It looks in the outermyScopeTestfunction's scope and finds it there.console.log(c)will cause aReferenceError: c is not defined. The variablecwas declared withlet, so it is block-scoped to theifstatement. It does not exist outside of those{}braces.
Conclusion
Fantastic work! This was a dense but incredibly important lesson. Understanding scope is like learning the rules of gravity in the JavaScript universe—it governs everything.
Key Takeaways:
- Scope defines where variables are accessible in your code.
- JavaScript has three main types of scope:
- Global Scope: Accessible everywhere.
- Function Scope: For variables declared with
var. Accessible only within that function. - Block Scope: For variables declared with
letandconst. Accessible only within the nearest{}.
- The Scope Chain is the process JavaScript uses to look for variables, moving from inner scopes to outer scopes.
- Best Practice: Use
constby default andletwhen you need to reassign a variable. Avoid usingvarto prevent scope-related bugs.
Next Up:
We've seen that a new execution context is created every time a function is called. But what happens when a function calls another function, which calls another? How does JavaScript keep track of all these active contexts? In our next lesson, we will visualize this process by learning about the Call Stack.