🔐 Mastering JavaScript Closures: The Secret Sauce Behind Top Interview Answer

krishankrishan
3 min read

Closures are one of the most asked JavaScript interview topics—but they’re often misunderstood. In this post, we’ll break them down with real-world examples, interview questions, and practical React use cases.


📌 What Are Closures?

A closure is a function that "remembers" the variables from its outer scope even after that scope has finished executing.

function outer() {
  let count = 0;
  return function inner() {
    count++;
    console.log(count);
  };
}

const counter = outer();
counter(); // 1
counter(); // 2

✅ Why it matters:

  • inner still has access to count even though outer() has finished running.

  • This is closure in action.


🎯 Beginner-Level Interview Questions

1. What is a closure in JavaScript?

A closure is a function that has access to variables in its outer (enclosing) function scope, even after the outer function has returned.

2. What will the following code output?

function createCounter() {
  let count = 0;
  return function () {
    count++;
    return count;
  };
}

const counter1 = createCounter();
console.log(counter1()); // ?
console.log(counter1()); // ?

Answer:
1 and 2, because count is preserved across function calls via closure.


🧠 Intermediate Questions

3. How do closures help in data privacy?

Closures allow us to create private variables:

function bankAccount() {
  let balance = 1000;
  return {
    deposit(amount) { balance += amount; },
    getBalance() { return balance; }
  };
}

const account = bankAccount();
account.deposit(500);
console.log(account.getBalance()); // 1500

balance is not directly accessible from outside — only via the methods inside the closure.


4. How do closures help avoid stale values in React?

React's useEffect + setInterval can trap stale state:

function Timer() {
  const [count, setCount] = useState(0);
  const countRef = useRef(count);

  useEffect(() => {
    countRef.current = count;
  }, [count]);

  useEffect(() => {
    const interval = setInterval(() => {
      console.log("Stale count:", count); // stale value
      console.log("Live count:", countRef.current); // fresh value
    }, 1000);

    return () => clearInterval(interval);
  }, []);

  return <button onClick={() => setCount(c => c + 1)}>Increment</button>;
}

Using useRef with closure helps access the latest value without re-running the effect.


🔍 Advanced Questions

5. What is a closure trap? How do you fix it?

If you use setTimeout or setInterval inside a closure, the variables it uses might be frozen in time:

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 1000);
}
// Output: 3 3 3

// Fixed with closure:
for (var i = 0; i < 3; i++) {
  (function (x) {
    setTimeout(() => console.log(x), 1000);
  })(i);
}
// Output: 0 1 2

6. Can closures lead to memory leaks?

Yes, if not managed properly. A long-lived closure holding large references can prevent garbage collection.

Example:

function createLeakyClosure() {
  const largeData = new Array(1000000).fill('leak');
  return () => console.log("Still here!");
}

const leaky = createLeakyClosure();
// `largeData` stays in memory because the function still exists

⚛️ React Interview Add-ons

7. How are closures used in custom hooks?

function useCounter() {
  const [count, setCount] = useState(0);

  const increment = () => setCount(c => c + 1);
  return { count, increment };
}

This increment uses closure to "remember" setCount.


✅ Summary

ConceptUse
ClosuresRemember state between function calls
Private variablesAvoid exposing data
React hooksHandle stale state with useRef
Memory leaksBe cautious with long-living closures

🧪 Final Challenge

What will this print and why?

function foo() {
  var secret = "🍕";
  return function () {
    return secret;
  };
}

var getSecret = foo();
secret = "🍔";
console.log(getSecret()); // ?

✍️ Written by Krishan — follow me on Twitter and GitHub and Linkedin

💡 Check out the current code examples and notes repo: GitHub

📝 Read more on my blog: Hashnode

0
Subscribe to my newsletter

Read articles from krishan directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

krishan
krishan

👋 Hey, I'm a Frontend Developer passionate about building clean, user-friendly interfaces. 🚀 Learning and sharing everything from React, JavaScript, HTML/CSS to advanced topics like Data Structures, Algorithms & System Design. 💻 Documenting my journey from fundamentals to becoming a top-tier developer — one blog at a time. 📚 Join me as I break down complex topics into easy, practical lessons — with GitHub repos, code snippets, and real-world examples. 🔁 Consistent growth, community learning, and aiming high!