A counter function returns a number that keeps going up between calls, but nothing outside can change it directly. Where is that number stored?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
The returned function still reaches count after makeCounter has finished.
function makeCounter() {
let count = 0;
return function () {
count += 1;
return count;
};
}
const next = makeCounter();
console.log(next(), next(), next());
03Objective and prerequisites
Learning objective: Create closures that remember variables after their outer function returns, use them for private state and function factories, and avoid the loop closure trap.
A closure is a function together with the variables it can reach from where it was written.
When an inner function is returned or stored, it keeps those outer variables alive, even after the outer function has finished.
Each call of the outer function creates a separate set of variables, so two counters made by makeCounter() count independently.
Closures give private state: code outside can use the returned functions but cannot read or change the variable directly.
Closures capture variables, not values: if the variable changes later, the closure sees the new value.
With var in a loop, every callback shares one variable, so all see its final value. let creates a fresh binding per iteration, fixing this.
Function factories (makeMultiplier(3)) and configured callbacks are everyday closures; so is every event handler that reads a variable from its surroundings.
A closure keeps everything it references alive. Holding large data in long-lived closures (for example in listeners never removed) can leak memory.
05Definitions
Closure
A function plus the outer variables it keeps access to from where it was defined.
Private state
Data reachable only through the functions that close over it.
Function factory
A function that creates and returns configured functions.
Captured variable
An outer variable that a closure keeps alive and can read or change.
A page creates a click handler for each product button. Each handler is a closure over its product's id, so the same handler code knows which product it belongs to without reading the page again.
function counter() { let n = 0; return () => ++n; }
const c = counter();
console.log(c(), c());
1 2
1 1
2 2
0 1
2. What does a closure keep access to?
Only global variables
The variables in scope where the function was defined
A copy of the caller's variables
Nothing after the outer function returns
3. What is printed?
const fns = [];
for (var i = 0; i < 3; i++) fns.push(() => i);
console.log(fns.map((f) => f()));
[0, 1, 2]
[3, 3, 3]
[undefined, undefined, undefined]
An error
4. Why is wallet.balance undefined?
function createWallet() { let balance = 10; return { get: () => balance }; }
const wallet = createWallet();
console.log(wallet.balance);
balance is a captured variable, not a property
balance was never set
Arrow functions cannot return
The wallet is frozen
5. What is printed?
const times = (f) => (n) => n * f;
const double = times(2);
console.log(double(3), double(4));
6 8
6 6
3 4
NaN NaN
6. How should a module keep a login attempt count that other code must not change directly?
A global variable
A let inside a factory, exposed only through functions
A property on window
A var in a loop
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Fix the shared counter: Prints 3 1; Fresh counter starts at 1
Greeter factory: Prints Hi, Ada!; Another greeting
Attempt limiter: Prints the attempts; State is private; Limiters are independent
ex-048-01: output matches the documented expected output
ex-048-02: output matches the documented expected output
ex-048-03: output matches the documented expected output
ex-048-04: output matches the documented expected output
ex-048-05: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-02-core-development/module-10-scope-and-javascript-behavior/lesson-048-closures/. Every example on this page is generated from those files.
The GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Academy) has not been published yet, so these links will work once it is. Until then, use the ZIP download above.
15Summary and next steps
A closure is a function plus the outer variables it can reach.
Captured variables stay alive after the outer function returns.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationclosures
Context: I am learning closures in JavaScript.
Task: Explain closures with a counter and a discount factory, and why each counter has its own state.
Constraints: Beginner-friendly language, short runnable examples, no libraries.
Expected behaviour: I can explain the idea in my own words and predict small programs.
Testing: Finish with three quick questions for me to answer.
Code predictionclosures drill
Context: I have practised closures.
Task: Give me six closure snippets, including the var loop trap, and ask what each prints.
Constraints: Wait for my answer before revealing each result.
Expected behaviour: Each question has exactly one correct output.
Testing: Explain any I miss with a step-by-step trace.
Debuggingclosures bug
Context: My callbacks all use the last value from a loop.
Task: Help me find the cause with questions instead of giving me the fix.
Constraints: Do not rewrite my program.
Expected behaviour: I locate and fix the bug myself.
Testing: Suggest the console.log lines that would reveal the problem.
Exercise generationclosures practice
Context: I finished the closures exercises.
Task: Create three exercises that use closures for private state and factories.
Constraints: Fictional data and exact expected output.
Expected behaviour: Each exercise has tests I can run.
Testing: Put the solutions in a separate hidden section.
Code reviewclosures review
Context: Here is my code that uses closures.
Task: Review my code for global state that could be a closure and for closures that hold large data unnecessarily.
Constraints: Explain each suggestion briefly and keep behaviour identical.
Expected behaviour: The code is clearer and has no hidden mutation or edge-case bug.
Testing: List the changes in order of importance.