What is a closure in JavaScript?
Understand closures in JavaScript — how inner functions remember variables from their parent scope.
Advertisement
Question
What is a closure in JavaScript?
Answer
A closure is created when a function remembers the variables from its outer scope even after the outer function has finished executing.
function makeCounter() {
let count = 0;
return function () {
count++;
return count;
};
}
const counter = makeCounter();
console.log(counter()); // 1
console.log(counter()); // 2
Here, the inner function “closes over” the count variable.
Real-World Example
Closures are used in React hooks, event handlers, and data encapsulation.
Quick Practice
Create a function createUser(name) that returns a function logging that name when called.
Summary
Closures let functions remember — they give JavaScript memory and encapsulation power.
Why are closures important?
They enable data privacy and maintain state between function calls.
Advertisement
Stay Updated
Get the latest frontend challenges, interview questions and tutorials delivered to your inbox.
Advertisement