1What is a closure? Give a practical example.
A closure is a function that remembers the variables from the scope where it was created, even after that outer function has finished running.
function createRateLimiter(limit) {
let calls = 0; // private state, kept alive by the closure
return function () {
if (calls >= limit) return false;
calls++;
return true;
};
}
const canCall = createRateLimiter(3);
canCall(); canCall(); canCall(); canCall(); // true true true falsePractical uses: private variables (nothing outside can change calls), function factories, memoization caches, and utilities like debounce, throttle and once. Mention the cost: closed-over variables stay in memory as long as the function is reachable.