Closures: Real-World Use Cases in JavaScript
Closures are used everywhere in real code. Here are the most common practical patterns.
Closures: Real-World Use Cases in JavaScript
Closures are not just an interview topic. They are used in real code every day. Here are the most common practical patterns.
1. Data Privacy
function createBankAccount() { let balance = 0; return { deposit: (amount) => { balance += amount; return balance; }, withdraw: (amount) => { balance -= amount; return balance; }, getBalance: () => balance, }; } const acc = createBankAccount(); acc.deposit(100); acc.getBalance(); // 100 // balance is private `` ### 2. Memoization ```js function memoize(fn) { const cache = {}; return (...args) => { const key = JSON.stringify(args); if (!(key in cache)) cache[key] = fn(...args); return cache[key]; }; } const fib = memoize((n) => n < 2 ? n : fib(n - 1) + fib(n - 2)); fib(40); // fast (cached) `` ### 3. Once Utility ```js function once(fn) { let done = false; let result; return (...args) => { if (done) return result; done = true; result = fn(...args); return result; }; } const init = once(() => { console.log("initializing"); return 42; }); init(); // logs "initializing", returns 42 init(); // returns 42 (no log) `` ### 4. Currying ```js function curry(fn) { return function curried(...args) { if (args.length >= fn.length) return fn(...args); return (...next) => curried(...args, ...next); }; } const sum = curry((a, b, c) => a + b + c); sum(1)(2)(3); // 6 `` ### 5. Event Handlers with State ```js function setupCounter(button) { let count = 0; button.addEventListener("click", () => { count++; button.textContent = `Clicked ${count}`; }); } `` ### 6. Throttle and Debounce ```js function debounce(fn, delay) { let timer; return (...args) => { clearTimeout(timer); timer = setTimeout(() => fn(...args), delay); }; } const search = debounce((q) => console.log("searching:", q), 300); input.addEventListener("input", (e) => search(e.target.value)); `` `timer` is closed over, so each call clears the previous timer. ### 7. Function Factories ```js function multiplier(factor) { return (n) => n * factor; } const double = multiplier(2); const triple = multiplier(3); double(5); // 10 triple(5); // 15 `` ### 8. Iterator-like Patterns ```js function makeIterator(arr) { let i = 0; return { next: () => (i < arr.length ? { value: arr[i++], done: false } : { done: true }), }; } const iter = makeIterator([1, 2, 3]); iter.next(); // { value: 1, done: false } iter.next(); // { value: 2, done: false } `` ### The Takeaway Closures power data privacy, memoization, once-utilities, currying, event handlers with state, throttle/debounce, function factories, and iterator patterns. Anywhere you need a function to remember variables from where it was defined, you are using closures.
Data privacy, memoization, once-utilities, currying, event handlers with state, throttle/debounce, function factories, and iterator-like patterns. Anywhere a function needs to remember variables from where it was defined, closures are used.
The memoize function closes over a cache object. The returned function checks the cache before calling the original function. If the result is cached, it returns immediately. Otherwise, it computes, stores, and returns. The cache is private to the closure.
They close over a timer variable. Each call clears the previous timer and sets a new one. The closed-over timer persists across calls, which is what makes debounce and throttle work.
A factory function takes a configuration parameter and returns a new function that closes over it. For example, multiplier(2) returns a function that always multiplies by 2. Each call to the factory creates a separate closure with its own parameter.
By declaring variables inside a function and returning methods that access them. The variables are in the function's lexical environment and cannot be accessed directly from outside, only through the returned methods. This is the module pattern.
Ready to master React completely?
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course to dive deeper with high-quality video tutorials, solve interview questions, and a premium community.
Master React
Want to upskill yourself, crack your next interview, and get your dream job? Join our comprehensive course.

