How to Explain JavaScript Closures in Your Interview

·6 min read
javascriptinterview-questionsclosuresfrontend

What single JavaScript concept powers React hooks, enables private variables, and appears in nearly every technical interview? Closures. They're so fundamental that they're built into the language itself—yet most candidates either over-explain them or can't give a practical example. Here's how to nail this question.

The 30-Second Answer

When the interviewer asks "What is a closure?", here's your concise answer:

A closure is a function that remembers the variables from its outer scope, even after the outer function has finished executing. It's like the inner function carries a backpack of variables wherever it goes.

That's it. Don't over-explain. Wait for follow-up questions.

The 2-Minute Answer (If They Want More)

If they ask you to elaborate:

In JavaScript, when you create a function inside another function, the inner function has access to three scopes: its own variables, the outer function's variables, and global variables.

What makes closures special is that this access persists even after the outer function returns. The inner function 'closes over' those variables, keeping them alive in memory.

This is useful for data privacy, creating factory functions, and maintaining state in callbacks.

Code Example to Show

Always be ready to write this:

function createCounter() {
  let count = 0;  // This variable is "closed over"
 
  return function() {
    count++;
    return count;
  };
}
 
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2
console.log(counter()); // 3

Explain it: "Even though createCounter has finished executing, the returned function still has access to count. Each call increments the same count variable. This is a closure in action."

The Classic Loop Problem (They WILL Ask This)

This question separates junior from senior developers:

for (var i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}

What gets logged? 3, 3, 3 (not 0, 1, 2)

Why? By the time the callbacks execute, the loop has finished and i is already 3. All three functions share the same i variable.

Three Ways to Fix It

1. Use let instead of var (Modern solution)

for (let i = 0; i < 3; i++) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
}
// Output: 0, 1, 2

let creates a new binding for each iteration.

2. Use an IIFE (Classic solution)

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

The IIFE captures i as j for each iteration.

3. Use forEach (Practical solution)

[0, 1, 2].forEach(function(i) {
  setTimeout(function() {
    console.log(i);
  }, 1000);
});
// Output: 0, 1, 2

Common Follow-Up Questions

"What are practical uses of closures?"

  1. Data privacy / Encapsulation
function createBankAccount(initialBalance) {
  let balance = initialBalance; // Private variable
 
  return {
    deposit: function(amount) {
      balance += amount;
      return balance;
    },
    getBalance: function() {
      return balance;
    }
  };
}
 
const account = createBankAccount(100);
account.deposit(50);     // 150
account.getBalance();    // 150
// account.balance       // undefined - can't access directly!
  1. Function factories
function multiply(x) {
  return function(y) {
    return x * y;
  };
}
 
const double = multiply(2);
const triple = multiply(3);
 
double(5);  // 10
triple(5);  // 15
  1. Event handlers and callbacks
function setupButton(buttonId, message) {
  document.getElementById(buttonId).addEventListener('click', function() {
    alert(message); // message is closed over
  });
}

"Are there any downsides to closures?"

Yes, mention these:

  1. Memory usage - Closed-over variables stay in memory as long as the closure exists
  2. Memory leaks - If closures reference large objects or DOM elements, they won't be garbage collected
  3. Debugging - Can be harder to track variable values across scopes

"How do closures relate to scope?"

"Closures are a result of lexical scoping in JavaScript. Lexical scope means a function's scope is determined by where it's written in the code, not where it's called. Closures leverage this by allowing inner functions to access outer variables based on where they were defined."

What Interviewers Are Really Testing

When I ask about closures, I'm checking:

  1. Conceptual understanding - Can you explain it simply?
  2. Practical application - Can you show a real use case?
  3. Problem-solving - Can you handle the loop problem?
  4. Depth of knowledge - Do you understand the tradeoffs?

A candidate who gives the 30-second answer, writes a clean example, and mentions memory considerations will stand out.

Quick Reference Card

QuestionKey Points
What is a closure?Function + its lexical environment
Why use closures?Data privacy, factories, callbacks
Loop problem causevar shares scope across iterations
Loop problem fixUse let, IIFE, or forEach
Downside?Memory usage, potential leaks

Practice Questions

Test yourself before your interview:

  1. What will this log and why?
function outer() {
  let x = 10;
  function inner() {
    console.log(x);
  }
  x = 20;
  return inner;
}
outer()();
  1. Create a function once(fn) that ensures fn can only be called once.
  2. Explain why this doesn't work and fix it:
for (var i = 0; i < 5; i++) {
  document.getElementById('btn' + i).onclick = function() {
    alert('Button ' + i + ' clicked');
  };
}


Related Articles

If you found this helpful, check out these related guides:

Ready for More JavaScript Interview Questions?

This is just one of 150+ JavaScript questions in our complete interview prep guide. Each question includes:

  • Concise answers for time-pressed interviews
  • Code examples you can write on a whiteboard
  • Follow-up questions interviewers actually ask
  • Insights from someone who's interviewed hundreds of developers

Get Full Access to All JavaScript Questions →

Or try our free JavaScript preview to see more questions like this.


Written by the EasyInterview team, based on real interview experience from 12+ years in tech and hundreds of technical interviews conducted at companies like BNY Mellon, UBS, and leading fintech firms.

Ready to ace your interview?

Get 550+ interview questions with detailed answers in our comprehensive PDF guides.

View PDF Guides