JavaScriptBasic
What is a Closure?
What is a Closure?
A closure is the ability of a function to remember and access its lexical scope even when the function is executed outside of that scope.
In short: Closure = Function + the scope environment in which it was defined.
Basic Example
function outer() {
const message = 'Hello'
function inner() {
console.log(message) // can access outer's message
}
return inner
}
const greet = outer()
greet() // 'Hello'
After inner is returned and outer has finished executing, inner still "remembers" the message variable — that's a closure.
Common Use Cases
- Data Privacy (Encapsulation): Use closures to simulate private variables, preventing direct external access
function createCounter() {
let count = 0
return {
increment() { count++ },
getCount() { return count }
}
}
const counter = createCounter()
counter.increment()
counter.getCount() // 1
// count cannot be accessed directly from outside
- Function Factories: Generate functions with specific behavior based on parameters
function multiplier(factor) {
return (num) => num * factor
}
const double = multiplier(2)
const triple = multiplier(3)
double(5) // 10
triple(5) // 15
- Debounce / Throttle: Use closures to preserve the timer ID
function debounce(fn, delay) {
let timer
return function (...args) {
clearTimeout(timer)
timer = setTimeout(() => fn.apply(this, args), delay)
}
}
Things to Keep in Mind
- Closures hold a reference to outer variables, not a copy — so changes to the outer variable are reflected inside the closure
- Excessive use of closures can cause memory leaks, as variables referenced by closures cannot be garbage collected
✦ AI Mock Interview
Type your answer and get instant AI feedback
Sign in to use AI scoring
