Closures in JavaScript – Understand Lexical Scope with Real Examples
Quick Answer: A closure happens when a function remembers variables from its outer scope. It can still access those variables after the outer function has finished running. JavaScript uses lexical scope to decide which variables a function can access.
Closures help us keep data private, create independent functions, and manage state. They are useful in callbacks, event handlers, timers, and many application patterns.
1. What Is a Closure in JavaScript?
Imagine a school collecting fees from students. Each student has a different total fee and paid amount.
The school needs to track each student's payments separately. It must also prevent one student's payment from changing another student's balance.
How can a function remember one student's details after it has finished running?
JavaScript closures solve this problem.
Lexical scope = variable access based on where code is written.
Closure = a function together with access to its outer lexical environment.
A function can access variables from three places:
- Its own local scope.
- The scope of its outer function.
- The global scope, when a matching variable exists there.
JavaScript decides this access from the function's written location. It does not depend on where the function gets called.
2. Understand the Problem Without Closures
Imagine a school has 1,000 students. Each student pays fees in several installments.
We need to track each student's total fee and paid amount. First, consider a simple approach without closures.
Example 1: Track fee payments using separate variables
This example works for three students. Each student needs separate variables.
let priyaTotalFee = 30000;
let priyaPaid = 10000;
let arjunTotalFee = 25000;
let arjunPaid = 5000;
let lakshmiTotalFee = 40000;
let lakshmiPaid = 15000;
priyaPaid += 5000;
arjunPaid += 3000;
lakshmiPaid += 10000;
console.log("Priya balance:", priyaTotalFee - priyaPaid);
console.log("Arjun balance:", arjunTotalFee - arjunPaid);
console.log("Lakshmi balance:", lakshmiTotalFee - lakshmiPaid);
Expected output
Priya balance: 15000 Arjun balance: 17000 Lakshmi balance: 15000
This works, but it gets hard to manage. We repeat variables and payment logic for every student.
What Goes Wrong as the School Grows?
- Every student needs a separate set of variables.
- Payment logic gets repeated in different places.
- One incorrect variable name can update the wrong student.
- Adding more students makes the code harder to maintain.
- Related data is not grouped together.
Now think about 1,000 students. We need a cleaner way to manage each account.
3. The Solution: Use Closures to Keep Student Data Private
We can create one function for each student's fee account.
The outer function stores the student's details. It returns an inner function that can update the payment amount.
That returned function keeps access to the outer variables. This access continues after the outer function returns.
Example 2: Create a private student fee account using a closure
Each call creates an independent account with its own payment state.
function createFeeAccount(studentName, totalFee) {
let paidAmount = 0;
function collectPayment(amount) {
paidAmount += amount;
console.log(
studentName + " paid: " + amount
);
console.log(
"Remaining balance: " + (totalFee - paidAmount)
);
}
return collectPayment;
}
const priyaAccount = createFeeAccount("Priya", 30000);
const arjunAccount = createFeeAccount("Arjun", 25000);
priyaAccount(10000);
priyaAccount(5000);
arjunAccount(5000);
arjunAccount(3000);
Expected output
Priya paid: 10000 Remaining balance: 20000 Priya paid: 5000 Remaining balance: 15000 Arjun paid: 5000 Remaining balance: 20000 Arjun paid: 3000 Remaining balance: 17000
Notice that we never create a global variable for each student.
Priya's function remembers Priya's details. Arjun's function remembers Arjun's details.
Compare the Two Approaches
| Without closures | With closures |
|---|---|
| Separate variables for every student. | One reusable account function. |
| Payment logic can be repeated. | Payment logic stays in one place. |
| Variables are easier to change accidentally. | Private variables are accessed through returned functions. |
| Adding students means adding more variables. | Call the account function for each student. |
| Related data is scattered. | Each account keeps its own state. |
The Idea to Remember
- Lexical scope = variable access based on where code is written.
- Outer function = the function that creates the inner function.
- Inner function = the function defined inside another function.
- Closure = the inner function and its remembered outer environment.
- Private state = data accessed through specific functions instead of direct outside access.
- Independent closure = a separate function instance with its own remembered variables.
4. How Lexical Scope Works
Before understanding closures deeply, we should understand lexical scope.
Lexical scope means JavaScript checks variables using the code's written structure.
Consider a school fee account. The outer function knows the student's name. The inner function can read that name.
Example 3: Read a variable from an outer function
function createStudentMessage() {
const studentName = "Priya";
function showMessage() {
console.log("Welcome, " + studentName);
}
showMessage();
}
createStudentMessage();
Expected output
Welcome, Priya
The inner function can read studentName. That variable belongs to its outer function.
Visual 1: Lexical Scope Lookup
The following diagram shows how the inner function finds a variable.
The lookup starts inside the function and moves outward until JavaScript finds the variable.
If JavaScript cannot find a variable in any accessible scope, it reports a reference error.
5. What Happens When the Outer Function Returns?
This is the most important part of closures.
Normally, local variables belong to a function call. You may expect them to disappear after that call ends.
However, a returned inner function may still need those variables. JavaScript keeps the required lexical environment available while it remains reachable.
Let's see this with a school fee account.
Example 4: Call the inner function after the outer function returns
function createFeeReminder(studentName) {
const message = "Please complete your fee payment";
return function () {
console.log(studentName + ": " + message);
};
}
const remindPriya = createFeeReminder("Priya");
// The outer function has already returned.
remindPriya();
remindPriya();
Expected output
Priya: Please complete your fee payment Priya: Please complete your fee payment
The returned function still knows studentName and message.
It does not need the outer function to run again. Its closure keeps the required variables accessible.
Visual 2: The Closure Keeps Its Environment
This diagram follows the function from creation to later execution.
The returned function keeps access to the variables it needs, even after the outer call ends.
Important: A closure does not freeze variable values. It retains access to the variables themselves. If a retained variable changes, later calls can read the updated value.
6. How JavaScript Closures Work Internally
JavaScript functions keep an internal reference to their lexical environment.
A lexical environment stores the variables available in a particular scope. It also links to an outer environment.
When a function is created, JavaScript records the environment where it was defined. When the function runs, variable lookup follows that environment chain.
Visual 3: Two Independent Student Accounts
Each call to createFeeAccount creates a separate function and state.
Each function instance keeps its own student details and payment amount.
These diagrams show the key closure behavior:
- Each function is created in a particular lexical environment.
- The returned function retains access to that environment.
- JavaScript keeps required variables available while they remain reachable.
- Separate function calls can create separate retained environments.
7. Closures with Private Variables
Closures can help us protect internal data from direct outside access.
In the fee account example, paidAmount is declared inside the outer function.
Code outside that function cannot access it by using the account function's name. The returned function provides controlled access.
Example 5: Expose payment methods, not the internal variable
function createFeeAccount(studentName, totalFee) {
let paidAmount = 0;
return {
collectPayment(amount) {
if (amount <= 0) {
console.log("Enter a valid payment");
return;
}
if (paidAmount + amount > totalFee) {
console.log("Payment exceeds the total fee");
return;
}
paidAmount += amount;
console.log(studentName + " payment accepted");
},
getBalance() {
return totalFee - paidAmount;
}
};
}
const priyaAccount = createFeeAccount("Priya", 30000);
priyaAccount.collectPayment(10000);
priyaAccount.collectPayment(5000);
console.log("Balance:", priyaAccount.getBalance());
console.log("Direct access:", priyaAccount.paidAmount);
Expected output
Priya payment accepted Priya payment accepted Balance: 15000 Direct access: undefined
The returned object exposes only the methods we choose. The internal variable stays outside direct access.
Security note: Closures provide data encapsulation inside JavaScript code. They are not a security boundary against malicious code running in the same application context.
8. Closures in JavaScript Callbacks
Closures are common in callbacks. A callback is a function passed to another function for later execution.
For example, a school may schedule a fee reminder. The reminder needs to remember the student's name.
Example 6: Remember a student's name inside a callback
function scheduleReminder(studentName) {
return function () {
console.log("Reminder for " + studentName);
};
}
const priyaReminder = scheduleReminder("Priya");
const arjunReminder = scheduleReminder("Arjun");
setTimeout(priyaReminder, 100);
setTimeout(arjunReminder, 200);
Expected output
Reminder for Priya Reminder for Arjun
The output appears after the scheduled delays. Each callback remembers its own student name.
9. Closures with Loops: A Common Interview Problem
Closures often appear in loop-related interview questions.
Consider a school that creates a reminder for three students. Each reminder should print its own number.
The Problem with var
The var keyword has function scope, not block scope. All callbacks below share the same loop variable.
Example 7: A loop with var and delayed callbacks
for (var i = 1; i <= 3; i++) {
setTimeout(function () {
console.log(i);
}, 100);
}
Expected output
4 4 4
The loop finishes before the callbacks run. At that point, i has the value 4.
Solution 1: Use let
The let keyword creates a new binding for each loop iteration.
Example 8: Use let for separate iteration values
for (let i = 1; i <= 3; i++) {
setTimeout(function () {
console.log(i);
}, 100);
}
Expected output
1 2 3
Solution 2: Create a Closure with an Inner Function
We can also create a separate function scope for each iteration.
Example 9: Capture each loop value using a closure
for (var i = 1; i <= 3; i++) {
(function (studentNumber) {
setTimeout(function () {
console.log(studentNumber);
}, 100);
})(i);
}
Expected output
1 2 3
The inner function remembers the value passed into its own parameter. This pattern uses an immediately invoked function expression, often called an IIFE.
Modern JavaScript: Prefer let or const for normal loop variables. The IIFE pattern remains useful when reading older JavaScript code.
10. Common Uses of Closures in Real Applications
10.1 Data Privacy
Keep internal values private and expose selected operations. The fee account example uses this pattern.
10.2 Event Handlers
An event handler can remember the values available when it was created.
function createClickHandler(studentName) {
return function () {
console.log(studentName + " selected");
};
}
const handlePriyaClick = createClickHandler("Priya");
handlePriyaClick();
Expected output
Priya selected
10.3 Function Factories
A function factory creates other functions with different settings.
function createDiscountCalculator(discountPercent) {
return function (amount) {
return amount - (amount * discountPercent / 100);
};
}
const studentDiscount = createDiscountCalculator(10);
const staffDiscount = createDiscountCalculator(15);
console.log(studentDiscount(1000));
console.log(staffDiscount(1000));
Expected output
900 850
10.4 Timers and Asynchronous Operations
Callbacks used by timers can retain access to their outer variables. This is common with setTimeout and setInterval.
10.5 Memoization
Memoization stores earlier results so later calls can reuse them. A closure can hold the cache privately.
function createFeeLookup() {
const feeCache = {};
return function (studentName, fee) {
if (feeCache[studentName] !== undefined) {
console.log("Using saved fee");
return feeCache[studentName];
}
feeCache[studentName] = fee;
console.log("Saving fee");
return fee;
};
}
const lookupFee = createFeeLookup();
console.log(lookupFee("Priya", 30000));
console.log(lookupFee("Priya", 30000));
Expected output
Saving fee 30000 Using saved fee 30000
This simple cache uses an object for demonstration. Production caches need clear limits and invalidation rules.
11. Common Closure Mistakes and Best Practices
Mistake 1: Thinking Closures Copy Values
A closure does not automatically copy a variable's value. It retains access to the variable binding.
Example 10: A closure reads the latest value
function createCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = createCounter();
console.log(counter());
console.log(counter());
console.log(counter());
Expected output
1 2 3
Mistake 2: Sharing One Variable Across Callbacks
Using var in a loop can make callbacks share one variable. Use let when each iteration needs its own binding.
Mistake 3: Keeping Unneeded Closures Alive
A closure can keep referenced data reachable. Long-lived references may increase memory use.
Release references when the application no longer needs them. Avoid retaining large objects unnecessarily.
Mistake 4: Assuming Closure Data Is Automatically Secure
Closures hide variables from direct access. They do not replace authentication, authorization, or server-side validation.
Mistake 5: Creating Too Much Hidden State
Closures can make state harder to inspect when used everywhere. Keep their purpose clear and expose simple methods.
Best Practices
- Use closures when a function needs to remember state.
- Keep the retained data as small as practical.
- Return only the operations that callers need.
- Use
letandconstfor predictable scope behavior. - Keep closure behavior easy to test.
- Do not use closures as a replacement for application security.
- Review long-lived callbacks and event listeners for retained references.
12. Closure vs Lexical Scope
These terms are related, but they describe different ideas.
| Lexical Scope | Closure |
|---|---|
| Defines where variables can be accessed. | Describes a function retaining access to its lexical environment. |
| Comes from the written structure of code. | Appears when a function uses variables from its outer environment. |
| Applies to ordinary nested functions. | Can keep outer variables available after the outer function returns. |
| Controls variable lookup. | Enables patterns such as private state and function factories. |
13. How Closures Come Up in Interviews
Question 1: What Is a Closure in JavaScript?
What the interviewer wants: They want to know whether you understand scope and retained variables.
Strong answer:
A closure is a function together with access to its outer lexical environment. The function can still access those variables after the outer function returns. I use closures to keep state private and create independent functions.
Question 2: Why Does a Closure Remember Variables?
Strong answer:
JavaScript functions keep a reference to the lexical environment where they were created. When a returned function uses an outer variable, that environment remains reachable. The function can then read or update the variable later.
Question 3: Can Two Closures Have Different Values?
Strong answer:
Yes. Each call to an outer function can create a separate lexical environment. For example, Priya and Arjun can have separate fee accounts. Each returned function updates only its own payment amount.
Question 4: Are Closures Used in Real Applications?
Strong answer:
Yes. We use closures in callbacks, event handlers, timers, and function factories. They also help keep internal state private. I choose them when a function needs to remember data between calls.
Question 5: What Is the Difference Between var and let in a Loop?
Strong answer:
var has function scope. A loop using var shares one binding across its iterations. let creates a separate binding for each iteration. That makes delayed callbacks easier to write correctly.
What Different Interview Levels Expect
- Junior: Explain lexical scope and write a basic closure.
- Mid-level: Explain callbacks, private state, and loop behavior.
- Senior: Discuss retained references, memory behavior, and maintainability.
- Architect: Explain where closures fit in application design and when explicit state management is clearer.
14. Hands-On Practice
Beginner: Create a Student Counter
Create a function named createStudentCounter. It should return a function that increases a private count.
Expected behavior: Calling the returned function three times should print 1, 2, and 3.
Intermediate: Create Separate Fee Accounts
Create fee accounts for Priya, Arjun, and Lakshmi. Each account should have its own total fee and paid amount.
Hint: Return an object with collectPayment and getBalance methods.
Advanced: Build a Payment Reminder Factory
Create a function that accepts a student's name and pending balance. Return a reminder function.
Expected behavior: Each reminder should print the correct student and balance, even when called later.
Challenge: Build a Private Cache
Create a closure that stores fee details by student name. Return a function that adds or reads entries.
Hint: Keep the cache inside the outer function. Do not expose the cache object directly.
15. Frequently Asked Questions
Does Every Inner Function Create a Closure?
A nested function has access to its outer lexical environment. The term closure is especially useful when that function retains and uses the environment beyond the outer function's execution.
Can a Closure Change an Outer Variable?
Yes. If the variable allows reassignment, the inner function can update it. A closure retains access to the variable binding.
Does a Closure Cause a Memory Leak?
Not automatically. A closure can keep referenced data reachable. Memory problems can happen when long-lived references retain data that is no longer needed.
Are Closures Available in Modern JavaScript?
Yes. Closures are a core JavaScript language feature. They work with modern browsers and current JavaScript runtimes.
Are Closures the Same as Classes?
No. Both can help organize state and behavior. Closures use lexical scope, while classes use JavaScript's class and prototype features.
16. Next Steps and Community
You now understand lexical scope and closures in JavaScript. You have seen how returned functions retain access to outer variables.
Try the fee account examples in your browser console. Change the values and observe how each closure behaves.
Explore the official documentation: MDN – JavaScript Closures.
Share your closure examples with the Upgradix community. Discuss different approaches and help other developers understand the concept.
Keep practising. Learn Technology. Build Your Future.