BugCast
JS JavaScript

JavaScript Closures: The #1 Interview Question

Master closures with real interview questions, code examples, and the mental model interviewers expect.

BugCast Admin··8 min read

What is a closure?

A closure is when a function remembers and can access variables from its outer (lexical) scope, even after that outer function has finished executing.

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

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

Common Interview Questions

Q: Explain closures in your own words.

Answer: A closure gives you access to an outer function's scope from an inner function.

Q: What's the output?

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

Why? var is function-scoped. Fix with let or an IIFE.

Key Points for Interviews

  • Closures enable data privacy (module pattern)
  • Used in callbacks, event handlers, and React hooks
  • Can cause memory leaks if large objects are retained unnecessarily
#closures#scope#interview

Related posts