🟨 JavaScript tutorial for beginners · Class 9 · Lesson 10 of 18 · Free
Closures – How JavaScript Functions Remember Variables
⏱ About 40 minutes · ▶ run real JavaScript here — nothing to install · no sign-in
In this lesson you will
- Explain scope: which variables a piece of code can see
- Create closures that remember and update their own private variables
- Use closures in real code: counters, wallets, click handlers and run-once functions
In Lesson 8, makeDiscount(20) returned a function that still knew "20 %" long after makeDiscount had finished. How? The function carried a little backpack of the variables around it. That backpack is called a closure, and it powers counters, private data, click handlers and much more.
What is scope in JavaScript?
Scope means "where a variable can be seen". A variable made with let or const lives inside the { } block where it was created.
Code inside can look OUTWARD and see outer variables. Code outside cannot look INSIDE a function or block.
Think of a house: from your room you can see the hall, but people in the hall cannot see inside your cupboard.
▶const school = "Sunrise School";23function classroom() {4 const teacher = "Mrs. Rao";5 console.log(teacher, "teaches at", school);6}78classroom();9console.log(school);10console.log(typeof teacher);
No variables yet.
▌✏️ Change this code and run it yourself
Mrs. Rao teaches at Sunrise SchoolSunrise Schoolundefined
💡 typeof teacher is "undefined" because teacher only exists inside classroom(). Try console.log(teacher) and see the error.
What is a closure in JavaScript?
A closure is a function together with the variables it could see when it was created. It keeps them alive even after the outer function has finished.
makeCounter() creates count, then returns a small function that uses count. makeCounter is finished, but count does not disappear, because the returned function still needs it.
Each call to counter() updates that same remembered count.
1function makeCounter() {2 let count = 0;3 return function () {4 count++;5 return count;6 };7}8▶const counter = makeCounter();10console.log(counter());11console.log(counter());12console.log(counter());
No variables yet.
▌✏️ Change this code and run it yourself
123
💡 Watch the animation: count is not a global variable, yet it keeps growing. Try it: add a fourth console.log(counter()).
Does each closure get its own copy of the variables?
Yes. Every time you call makeCounter(), a NEW count is created. The function it returns remembers that new one.
So two counters never mix up. Below, the India and Australia scores are counted separately.
A closure remembers the variable itself, not a frozen copy. If the variable changes, the function sees the new value.
1function makeScorer(team) {2 let runs = 0;3 return (r) => {4 runs += r;5 const score = `${team}: ${runs}`;6 console.log(score);7 };8}9▶const india = makeScorer("India");11const aus = makeScorer("Australia");12india(4);13india(6);14aus(1);
No variables yet.
▌✏️ Change this code and run it yourself
India: 4India: 10Australia: 1
💡 Try it: make a third team and add some runs. Does it change India's score?
How do closures keep data private in JavaScript?
Anything inside the outer function is private. Nobody outside can read or change it directly.
Below, balance can only change through deposit() and spend(). spend() also checks the rule: you cannot spend more than you have.
This is called data hiding. It stops bugs where some other code changes a value by mistake.
Diya: not enough money!Diya has ₹50undefined
💡 wallet.balance is undefined: balance is hidden inside the closure, not a key of the object.
How are closures used with click events?
Each event handler is a function, so it can be a closure too. Here makeLikeButton() is called once per button.
Every button gets its own private likes variable. Click the buttons and watch each count go up on its own.
Without closures you would need a separate global variable for every button.
📄 HTML of the page (tap to see / edit)
3 like buttons ready
💡 button.dataset.food reads the data-food="…" value from the HTML.
How do I make a function that runs only once?
A closure can remember "has this happened already?". once(fn) returns a new function that calls fn the first time and then ignores every other call.
Real use: a "Submit" button that must not send the form twice, or a welcome message shown one time only.
The done flag and the saved result live in the closure, safe from the outside.
Form sent for AaravForm sent for AaravForm sent for Aarav
💡 Try it: remove done = true; and run again. Now every call sends the form.
🤔 Predict the output
Think like JavaScript: read the code and choose what it prints. You get the reason straight away.
Question 1. What does this print?
function make() {
let n = 10;
return () => ++n;
}
const f = make();
f();
console.log(f());Question 2. What does this print?
function makeCounter() {
let count = 0;
return () => ++count;
}
const a = makeCounter();
const b = makeCounter();
a();
a();
console.log(b());Question 3. What does this print?
let x = 1;
function show() {
console.log(x);
}
x = 5;
show();🧩 Your challenge
Make a pocket-money tracker with a closure. makeTracker(name, limit) returns an object with add(amount, item) and report(). add() must refuse a purchase that goes over the monthly limit and print a warning. report() prints the total spent and what is left. Make two trackers that do not mix. Expected output (for the solution's calls): Riya bought Pen (₹20) Riya bought Comic (₹150) Riya cannot buy Cricket ball (₹200): limit ₹300 Riya spent ₹170, ₹130 left Arjun spent ₹0, ₹500 left
Riya bought Pen (₹20) Riya bought Comic (₹150) Riya cannot buy Cricket ball (₹200): limit ₹300 Riya spent ₹170, ₹130 left Arjun spent ₹0, ₹500 left
⚠️ Common mistakes (and how to fix them)
❌ Wrong
function makeSecret() {
const pin = 4321;
return () => "PIN is set";
}
makeSecret();
console.log(pin);ReferenceError: pin is not defined
✅ Right
function makeSecret() {
const pin = 4321;
return (guess) => guess === pin;
}
const check = makeSecret();
console.log(check(1234), check(4321));Variables inside a function are not visible outside it. To use them, return a function that works with them for you.
❌ Wrong
for (var i = 1; i <= 3; i++) {
setTimeout(() => console.log("Period", i), 100);
}No error, but it prints "Period 4" three times: by the time the timers run, the loop has finished and the single var i is already 4.
✅ Right
for (let i = 1; i <= 3; i++) {
setTimeout(() => console.log("Period", i), 100);
}var makes ONE shared i for the whole loop, so all three callbacks see its final value. let makes a new i for every round, so each closure remembers its own.
❌ Wrong
function makeCounter() {
let count = 0;
return () => ++count;
}
console.log(makeCounter()());
console.log(makeCounter()());No error, but it prints 1 and 1 instead of 1 and 2: every line made a new counter.
✅ Right
function makeCounter() {
let count = 0;
return () => ++count;
}
const counter = makeCounter();
console.log(counter());
console.log(counter());Each makeCounter() call makes a brand-new count starting at 0. Call it once, save the returned function, and call that again and again.
📌 Remember
- Scope decides where a variable can be seen: inner code sees outer variables, not the other way round.
- A closure is a function plus the variables around it when it was created.
- The remembered variables stay alive and can be updated after the outer function has finished.
- Every call to the outer function makes a fresh, separate set of variables.
- Use closures for counters, private data (like a wallet balance), event handlers and run-once functions.
- Use let, not var, in loops with timers or events so each round keeps its own value.
Finished the quiz and the challenge?
Questions students ask
What is a closure in JavaScript in simple words?
A closure is a function that remembers the variables from the place where it was made. Even after the outer function finishes, the inner function can still read and change those variables. In JavaScript every function is a closure, but it matters most when a function is returned or used later.
Why are closures useful?
They let you keep data private and remember state without global variables. Counters, click handlers, timers, and functions like makeDiscount(20) from Lesson 8 all rely on closures.
Do closures use a lot of memory?
A closure keeps its variables alive as long as the function is still in use. That is usually tiny. Only if you keep thousands of closures you no longer need does it matter, and normal apps rarely do that.
Are closures asked in coding interviews?
Yes, closures are one of the most common JavaScript interview topics, especially the counter example and the var-in-a-loop puzzle. If you understand this lesson, you can explain both.