Scope &
Closures
Master how JavaScript organizes variables, controls access, and enables powerful patterns through closures.
What Is Scope?
Scope determines where in your code a variable can be accessed. Think of it as a set of rules that governs how the JavaScript engine looks up variable names at any given point during execution.
The Three Types of Scope
Why Scope Matters
Scope is not just an abstract concept: it directly impacts how you write, debug, and organize real JavaScript code every day.
The Scope Chain
When JavaScript encounters a variable name, it searches for it in the current scope first, then walks outward through each enclosing scope until it finds a match or reaches the global scope.
The Core Rule: Lexical Scope
This is called lexical (or static) scoping. The word "lexical" means "relating to the text": the engine reads the nesting structure of your code to decide which variables each function can access.
var vs let vs const
| var | let | const | |
|---|---|---|---|
| Scope | Function | Block | Block |
| Hoisted? | Yes (as undefined) | Yes (TDZ) | Yes (TDZ) |
| Re-assignable? | Yes | Yes | No |
| Re-declarable? | Yes | No | No |
| Best practice | Avoid | Default | Prefer |
What Is a Closure?
When a function is defined inside another function and is then returned or passed elsewhere, it carries a hidden reference to its original scope. That "backpack" of variables is the closure.
How Closures Work
How to Recognize a Closure
Example 1: Basic Closure
Example 2: Private Counter
Example 3: The Loop Trap
Common Mistakes
Scope & Closures Summary
| Concept | What It Is | Key Behavior |
|---|---|---|
| Global Scope | Outermost level | Accessible everywhere |
| Function Scope | Inside a function | var lives here |
| Block Scope | Inside { } | let/const live here |
| Scope Chain | Lookup mechanism | Inner → Outer → Global |
| Closure | Function + environment | Remembers outer vars |
| Lexical Scope | Scope by position | Defined at write-time |
Question 1 of 5
In JavaScript, scope is best described as:
Question 2 of 5
Consider this code:
function outer() {
let secret = 42;
return function inner() {
return secret;
};
}
const reveal = outer();
console.log(reveal());
What does console.log(reveal()) output?
Question 3 of 5
Consider this code:
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
}
What is logged to the console?
Question 4 of 5
What does "lexical scope" mean?
Question 5 of 5
A closure captures a variable by: