Skip to main content
JavaScript Beginner Practical Coding Topic: Scope & Lexical Closures

Explain closures in JavaScript with a practical example

Quick Summary: A closure is created when an inner JavaScript function retains live access to variables from its outer lexical scope even after the outer function has finished executing and returned.

Written by Ravi Shankar Mishra (Founder & Lead Systems Architect, MockAttempt Academy) Reviewed by MockAttempt Engineering Editorial Desk
Last verified:

Direct Interview Answer

In JavaScript, functions carry a hidden reference to their birth lexical environment. Even when an outer factory function completes and its call-stack frame pops, any variables referenced by the returned inner function remain alive in heap memory.

Detailed Technical Explanation

Closures power data privacy/encapsulation, React hook callbacks, memoization caches, and event handler factories. Note two interview subtleties: (1) closures capture variable bindings, not snapshots—hence classic var loop bugs fixed by block-scoped let; and (2) unused large objects referenced inside a closure stay pinned in memory until the closure itself becomes unreachable.

Practical Walkthrough

Private counter & once-only initializer built cleanly with closures.

Code Example — JAVASCRIPT
function createRateLimiter(limit) {
    let remaining = limit;
    return function consumeRequest() {
        if (remaining <= 0) {
            return "Blocked: quota exhausted";
        }
        remaining--;
        return `Allowed (remaining: ${remaining})`;
    };
}

const attempt = createRateLimiter(2);
console.log(attempt());
console.log(attempt());
console.log(attempt());
Expected Output / Verification
Allowed (remaining: 1)
Allowed (remaining: 0)
Blocked: quota exhausted

Real-World Production Use Case

Implementing UI debounce/throttle wrappers, React custom hooks, private SDK tokens, and memoized selectors.

Common Interview Mistakes to Avoid

  • Creating stale closures in React useEffect when dependency arrays omit referenced state variables.
  • Using var inside a loop of setTimeout callbacks so every callback reads the final incremented counter.
Topics: #javascript #closures #scope #lexical-environment
Learn. Practise. Prove. Get Career-Ready.

Ready to Build Your IT Career?

Explore industry-led programmes and develop practical skills through training, assessments and interview preparation.