JavaScript Closures and Scope Exercises
Lexical scope, closures, and private state
Follow where JavaScript finds and remembers values
Practise lexical scope, closure behaviour, and private state by tracing real JavaScript execution. These exercises help you see which binding a function can access, what remains available after an outer call finishes, and how closures support reusable patterns.
- Exercises
- 20
- Difficulty
- Beginner to Hard
- Good to know first
- Be confident declaring and calling functions and reading nested function bodies.
What you’ll practise
- Global, function, and block scope
- Lexical scope lookup
- Closure state
- Private values and factories
- Module-style patterns
Challenges
Scope Chain Lookup
Scope Chain Lookup
The scope chain is the path JavaScript follows when code reads a variable name. ...
Function Scope
Function scope means variables declared inside a function belong to that functio...
Variable Shadowing
Variable shadowing happens when an inner scope declares a name that also exists ...
Block Scope
Block scope means a `let` or `const` variable declared inside braces belongs to ...
Lexical Scope
Lexical scope means a function's variable access is determined by where the func...
Closure Over Configuration
A closure forms when an inner function keeps access to a variable from an outer ...
Private State With Closures
A closure can keep state alive without putting that state in the global scope. E...
Saved Values
Closures are often used to split setup from use. The outer function receives a v...
Loop Closures
Closures capture variables, not snapshots of values. With `var), a loop has one ...
Stateful Closures
A closure can remember how many times something has happened. That state lives b...
Private Collections
Closures can protect collection state by keeping the actual array inside an oute...
Once Wrappers
A once wrapper is a closure that controls whether another function is allowed to...
Memoization
Memoization uses a closure to remember previous inputs and results. The wrapped ...
Shared Closure State
Multiple functions returned from the same outer function close over the same var...
Function Factories
A function factory creates functions that carry their own closed-over configurat...
Accidental Shared State
Closures are useful because they keep state alive, but the location of that stat...
Keyed Memoization
Implement keyed memoization with JavaScript closures, a private cache, and a key...
Closure State Machines
Build a JavaScript closure-based history store with private current state and un...
Closure Modules
Build a subscription hub with JavaScript closures, private listener state, and s...
Closure-Based Guards
Model a rate-limit token bucket with JavaScript closure state, capacity rules, r...