Hello! Welcome to the final lesson in our module on JavaScript's core mechanics.
In our last few lessons, we've explored the "invisible" machinery of JavaScript: the execution context, the scope chain, and how closures give functions a "memory." Most recently, you learned how to harness closures to create private data and organize code using the Module Pattern.
Today, we'll look at the other side of the coin. We will use our deep understanding of these concepts to identify common scope-related bugs and apply best practices to avoid them. Mastering this is not just about fixing errors; it's about writing clean, predictable, and professional-grade code—an essential skill for building complex applications with Next.js and TypeScript.
Let's dive in and learn how to sidestep the common pitfalls of scope.
Bug #1: Polluting the Global Scope
One of the most common bugs for beginners is accidentally creating variables in the global scope. This happens when you assign a value to a variable that hasn't been declared with var, let, or const.
function setStatus(status) {
// Whoops! 'message' was never declared.
message = `The status is: ${status}`;
}
setStatus('Processing');
console.log(message); // "The status is: The status is: Processing"
Why does this happen?
Recall the scope chain. When the JavaScript engine tries to assign a value to message inside setStatus, it first looks in the function's local scope. Not finding it, it goes up the scope chain to the global scope. In non-strict mode, if it still can't find the variable, it assumes you wanted to create a new one and helpfully creates message on the global object (window in the browser).
This "helpfulness" is dangerous. It can lead to hard-to-find bugs where different parts of your application accidentally overwrite each other's global variables.
The Best Practice: Use Strict Mode
JavaScript provides a way to prevent this silent error: Strict Mode. By placing the string 'use strict'; at the top of your file or function, you opt into a more restrictive and safer version of JavaScript.
'use strict';
function setStatus(status) {
// In strict mode, this will now throw an error.
message = `The status is: ${status}`;
}
// This call will fail before it can pollute the global scope.
// setStatus('Processing'); // Uncaught ReferenceError: message is not defined
Strict mode turns silent errors into loud, obvious ones, which is always better. Modern JavaScript tools, including modules which you'll learn about later, enable strict mode by default. It's a fundamental best practice.
The Fix: Always declare your variables.
'use strict';
function setStatus(status) {
let message = `The status is: ${status}`; // Correctly declared!
console.log(message);
}
setStatus('Complete'); // "The status is: Complete"
// console.log(message); // ReferenceError: message is not defined (as it should be!)
Bug #2: The Temporal Dead Zone (TDZ)
You know that let and const are block-scoped, which is safer than the function-scoped var. However, their behavior during the "hoisting" process can lead to a specific type of error if you're not careful.
Let's look at a classic tricky interview question:
let x = 'Global';
function checkScope() {
console.log(x); // What will this log?
let x = 'Local';
console.log(x);
}
checkScope();
You might expect the first console.log(x) to print "Global," because the let x = 'Local' declaration hasn't been reached yet. However, running this code results in a ReferenceError.
Why does this happen?
This is due to the Temporal Dead Zone (TDZ). During the execution context's creation phase, the JavaScript engine sees the let x declaration within checkScope. It "hoists" the variable by acknowledging its existence within that scope, but it does not initialize it.
The variable x is in a "dead zone" from the start of the function block until the line let x = 'Local' is executed. Any attempt to access it in this zone results in a ReferenceError. Because the engine knows a local x exists, it doesn't bother looking up the scope chain for the global x.
The following video provides an excellent visual walkthrough of how the TDZ works for let and const during the creation and execution phases of the execution context.
Master JavaScript Execution Context — Hoisting, Scope & Closures Made Clear
To understand the TDZ visually, let's watch a segment from the 'Master JavaScript Execution Context' video. It beautifully illustrates why let and const behave this way.
Watch the clip from 00:33:41 to 00:37:34. Pay close attention to the explanation of how let and const are handled during the loading phase, remaining in the TDZ, which contrasts with how var is initialized to undefined.
The Best Practice: Declare Before Use
The TDZ is actually a feature, not a bug. It helps you avoid using variables before they are intentionally declared, leading to more predictable code.
- Always declare variables at the top of their scope (function or block). This makes your code easier to read and eliminates any chance of hitting the TDZ.
- Prefer
constandletovervar. Their stricter rules and the TDZ help you catch potential bugs early.
Bug #3: The Classic Closure-in-a-Loop Problem
This is one of the most famous JavaScript "gotchas" and perfectly illustrates the practical difference between var and let in loops.
Imagine we're creating an "army" of functions. Each function should log its own number.
function makeArmy() {
const shooters = [];
var i = 0;
while (i < 5) {
shooters.push(function() {
console.log(i); // Each function should log its 'i'
});
i++;
}
return shooters;
}
const army = makeArmy();
army[0](); // Expected: 0, Actual: 5
army[2](); // Expected: 2, Actual: 5
army[4](); // Expected: 4, Actual: 5
Every function logs 5! Why?
Why does this happen?
All the functions created in the loop are closures. With var i, there is only one i variable that lives in the scope of the makeArmy function. All ten closures are created in this same scope and they all share a reference to this same i variable. By the time any of the army functions are called, the while loop has already completed, and the final value of i is 5.
To see a detailed step-by-step explanation and the solution, let's turn to a task from a trusted resource.
The article from javascript.info provides a fantastic explanation of this exact problem and presents two clean solutions.
Please read the task titled 'Army of functions'. Focus on the explanation of why all shooters show the same value. Then, carefully study the fix using let in a for loop and understand why it works.
The Best Practice: Use let in Loops
As the article explains, the modern and simplest solution is to use let to declare the loop counter.
function makeCorrectArmy() {
const shooters = [];
// Using 'let' fixes the problem!
for (let i = 0; i < 5; i++) {
shooters.push(function() {
console.log(i);
});
}
return shooters;
}
const correctArmy = makeCorrectArmy();
correctArmy[0](); // 0
correctArmy[2](); // 2
correctArmy[4](); // 4
This works because let is block-scoped. In a for loop, a new lexical environment with a new i variable is created for each iteration of the loop. Each closure captures the i from its specific iteration, preserving the correct value.
Test your understanding!
You have an array of user IDs. For each ID, you want to log a welcome message to the console after a 1-second delay.
const userIDs = [101, 102, 103];
for (var i = 0; i < userIDs.length; i++) {
setTimeout(function() {
console.log(`Welcome, user ${userIDs[i]}`);
}, 1000);
}
What will be logged to the console, and why? How would you fix it?
Show answer
The code will log:
Welcome, user undefined
Welcome, user undefined
Welcome, user undefined
This is the same closure-in-a-loop problem. The setTimeout callbacks are all created within the same function scope. By the time they execute (after 1 second), the for loop has already finished. The final value of i is 3, and userIDs[3] is undefined.
The Fix: Simply change var to let.
const userIDs = [101, 102, 103];
for (let i = 0; i < userIDs.length; i++) {
setTimeout(function() {
console.log(`Welcome, user ${userIDs[i]}`);
}, 1000);
}
Now, each setTimeout callback closes over a new i variable that is unique to its loop iteration, logging the correct user ID.
A Summary of Best Practices
To write robust, modern JavaScript and avoid these common bugs, follow these rules:
- Always Use `'use strict';': It prevents silent errors like accidental global variable creation.
- Prefer
const, thenlet, Avoidvar:const: Use by default for any variable you don't plan to reassign. This prevents accidental reassignment.let: Use only when you know a variable needs to be reassigned, like a loop counter.var: Avoid it. Its function-scoping and hoisting behavior are common sources of bugs.letandconstare block-scoped, which is more intuitive and less error-prone.
- Declare Variables Before Use: To avoid TDZ errors, declare all your variables at the top of their relevant block or function.
The following short video provides a great summary of why const and let are preferable to var.
Differences Between Var, Let, and Const
This video from Web Dev Simplified offers a final, concise recommendation on when to use const, let, and var.
Watch the final summary from 06:58 to 08:22. It reinforces the best practice of defaulting to const and using let only when necessary, while avoiding var.
Conclusion
Congratulations on completing this deep dive into JavaScript's execution model! You've moved from the basics of variables to the intricate mechanics of scope, hoisting, and closures. Most importantly, you've learned to identify and prevent the subtle bugs that trip up even experienced developers.
Key Takeaways:
- Scope-related bugs often arise from misunderstandings of how JavaScript handles variable declarations and lifetimes.
- Global Scope Pollution is a silent error caused by undeclared variables, which can be prevented by using
'use strict';. - The Temporal Dead Zone (TDZ) for
letandconstis a safety feature that prevents you from using a variable before its declaration, unlikevarwhich is initialized asundefined. - Closures in loops can behave unexpectedly with
varbecause all closures share the same variable. Using block-scopedletsolves this by creating a new variable for each loop iteration. - Adopting modern best practices—
'use strict';and preferringconst/letovervar—is the most effective way to write safer, more predictable code.
Next Up:
You now have a solid foundation in how JavaScript manages variables and functions "under the hood." In our next module, we will build on this by exploring another fundamental pillar of the language: Objects. You will learn how to create and manage collections of related data and functionality, which is central to almost everything you'll do in JavaScript.