55 Mins upper-intermediate
14. Scope & Closures
Core Mechanics
Scope & Closures
Scope defines where variables are accessible in your code. Closures are one of the most notoriously confusing concepts in JavaScript, but they are crucial for advanced architecture.
๐ Global vs Local Scope
Variables declared outside any function or block are in the Global Scope. Variables declared inside a block (using let or const) are trapped inside that block (Local Scope).
const globalVar = "I am everywhere";
if (true) {
const localVar = "I am trapped";
console.log(globalVar); // Works
}
// console.log(localVar); // ReferenceError: localVar is not defined
OutputI am everywhere
๐ The Magic of Closures
A closure occurs when a function "remembers" the variables in its surrounding scope even after the outer function has finished executing. It is a way to create private, persistent memory.
function createCounter() {
let count = 0; // This variable is protected
// This returned function remembers 'count' forever
return function() {
count++;
return count;
};
}
const counterA = createCounter();
console.log(counterA()); // 1
console.log(counterA()); // 2
console.log(counterA()); // 3
// You cannot access 'count' directly from the outside.
// console.log(count); // Undefined
Output1
2
3
2
3
Why this matters: Closures are used to create private variables, maintain state in React Hooks (like
useState), and implement the Module pattern.Knowledge Check
Ready to test your understanding of 14. Scope & Closures?