Closure
Closure
The ability of a function to remember variables from the environment in which it was declared. A core concept in JavaScript, Python, and others.
Closure
The ability of a function to remember variables from the environment in which it was declared. A core concept in JavaScript, Python, and others.
A closure is the ability of a function to remember and access the variables of the environment (lexical environment) in which it was declared. It is called a closure because the function "closes over" the scope of the outer function and carries it along. It is a core concept in languages that support first-class functions, such as JavaScript, Python, and Swift.
A closure is formed when an inner function accesses variables of an outer function. Even after the outer function has finished executing, the inner function can still reference the outer function's variables. This is because the variables are kept in memory rather than garbage collected.
Major uses of closures include data hiding (implementing private variables), factory functions, currying, and preserving state in event handlers. React's useState hook also uses closures to preserve state.
Closures are powerful but need care. Creating closures in a loop can cause variable capture timing problems, and unnecessary closures can cause memory leaks. Using the let keyword or an immediately invoked function expression (IIFE) solves these problems.
// JavaScript 클로저 예제
// 1. 기본 클로저
function createCounter() {
let count = 0; // private 변수
return {
increment: () => ++count,
decrement: () => --count,
getCount: () => count
};
}
const counter = createCounter();
console.log(counter.increment()); // 1
console.log(counter.increment()); // 2
console.log(counter.getCount()); // 2
// 2. 팩토리 함수
function createMultiplier(multiplier) {
return (number) => number * multiplier;
}
const double = createMultiplier(2);
const triple = createMultiplier(3);
console.log(double(5)); // 10
console.log(triple(5)); // 15
// 3. 루프에서 클로저 문제 (var 사용 시)
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
} // 3, 3, 3 출력 (의도치 않은 결과)
// 해결: let 사용
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 100);
} // 0, 1, 2 출력 (정상)
// 4. 이벤트 핸들러에서 클로저
function setupButton(buttonId, message) {
document.getElementById(buttonId).addEventListener('click', () => {
alert(message); // message를 클로저로 캡처
});
}
Senior: This component needs to reference the previous state value, and a closure can solve that.
Junior: How do I get the previous value of useState?
Senior: Just pass a function to setState, like prev => prev + 1. The closure makes it capture the latest state.
Interviewer: Please explain what a closure is and when it is useful.
Candidate: A closure is the ability to remember the lexical environment at the time a function is declared. It is useful for data hiding, state preservation, and the factory pattern. For example, in a counter function, it lets you manipulate the count variable while preventing direct access to it from outside.
Interviewer: What are the drawbacks or things to watch out for with closures?
Candidate: Captured variables are not garbage collected, which can cause memory leaks. Also, using var in a loop captures unintended values, so you should use let.
Take a mock interview on this topic → WIA SOOM AI Interview · Start for free
Reviewer: This event handler captures index in a closure. Is there a memory leak?
Author: It's fine if we remove the event listener when the component unmounts, right?
Reviewer: Right. Call removeEventListener in the cleanup function. That also releases the variables the closure references.