# Closures & Lexical Scope

> What is a closure in JavaScript? Explain with examples and real-world use cases.

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-closures-interview
Last updated: 2026-11-28

Difficulty: Intermediate

## Question

What is a closure in JavaScript? Explain with examples and real-world use cases.

## Answer

A closure is a function that remembers and has access to variables from its outer (enclosing) function's scope, even after the outer function has returned. Closures are created every time a function is created.

Key points:

1. A closure gives you access to an outer function's scope from an inner function.
2. Closures are commonly used for data privacy, function factories, and partial application.
3. Variables in a closure are references (not copies), so they reflect the latest value.

**How a closure keeps its scope alive. Watch makeCounter's scope survive after it returns. Switch to the loop or memoize examples under Tweak.**

1. **Calling the outer function creates a scope**: makeCounter() creates an environment record holding count.
2. **The inner function remembers it**: The returned arrow stores a hidden \[\[Environment\]\] link to that scope.
3. **The scope outlives the call**: The stack frame is popped, but the scope stays reachable through the arrow.
4. **Each call updates the same variable**: a() follows \[\[Environment\]\] to count and increments it: 1, then 2.
5. **A second factory call means separate state**: b gets a brand-new scope, so its count starts again from the beginning.

## Code examples

### Basic Closure

```
function outer() {
  let count = 0;
  return function inner() {
    count++;
    return count;
  };
}

const counter = outer();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3
```

inner() forms a closure over 'count'. Even after outer() returns, inner() still has access to count.

### Data Privacy with Closures

```
function createBankAccount(initialBalance) {
  let balance = initialBalance;

  return {
    deposit(amount) {
      balance += amount;
      return `Deposited ${amount}. Balance: ${balance}`;
    },
    withdraw(amount) {
      if (amount > balance) return 'Insufficient funds';
      balance -= amount;
      return `Withdrew ${amount}. Balance: ${balance}`;
    },
    getBalance() {
      return balance;
    }
  };
}

const account = createBankAccount(100);
console.log(account.deposit(50));
console.log(account.withdraw(30));
console.log(account.getBalance());
```

balance is private - it can only be accessed through the returned methods. This is the module pattern.

### Classic Loop Problem

```
// Problem: all callbacks log 3
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log('var:', i), 100);
}

// Fix 1: use let (block scoping)
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log('let:', j), 200);
}

// Fix 2: use IIFE closure
for (var k = 0; k < 3; k++) {
  (function(k) {
    setTimeout(() => console.log('iife:', k), 300);
  })(k);
}
```

var is function-scoped, so all callbacks share the same i. let creates a new binding per iteration. IIFE captures each value.

## Key points

- Every function in JavaScript creates a closure
- Closures can lead to memory leaks if large objects are retained unintentionally
- The module pattern uses closures to create private state

## Common follow-up questions

- What is the difference between closure and scope?
- How can closures cause memory leaks?
- Explain the module pattern using closures

## Interview tips

- Start with the definition, then immediately show a simple example
- Mention practical uses: data privacy, event handlers, partial application
- The loop + setTimeout question is extremely common - know all three fixes

## Concepts covered

Closures, Lexical Scope, Data Privacy, Function Factory

Previous: [JSON: parse, stringify & Common Pitfalls](https://www.internhack.in/learn/interview/javascript-interview/js-json-parse-stringify) · Next: [Hoisting & Temporal Dead Zone](https://www.internhack.in/learn/interview/javascript-interview/js-hoisting-interview) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [Object Methods & Property Descriptors](https://www.internhack.in/learn/interview/javascript-interview/js-object-methods)
- [this Keyword & Binding Rules](https://www.internhack.in/learn/interview/javascript-interview/js-this-keyword)
- [call, apply, bind](https://www.internhack.in/learn/interview/javascript-interview/js-call-apply-bind)
- [Prototypes & Prototype Chain](https://www.internhack.in/learn/interview/javascript-interview/js-prototypes)
- [Classes & Inheritance](https://www.internhack.in/learn/interview/javascript-interview/js-classes-inheritance)
- [Promises Deep Dive](https://www.internhack.in/learn/interview/javascript-interview/js-promises-deep)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
