Fossils🧠 ConceptualExplain Closures and this
ðŸĢHatchlingJavaScriptFundamentalsClosures

Explain Closures and this

Two of the most-asked JavaScript concepts. Your explanation reveals whether you understand the language's execution model or just memorized definitions.

Explain Closures and this

Interview Question: "Explain closures in JavaScript. How does this work?"

The Closure Answer

Don't say "a function that remembers its scope." Say:

"A closure is formed when a function retains access to its lexical environment after the enclosing function has returned. The inner function holds a reference to the outer function's variable environment — those variables stay alive as long as the closure exists."

The Demonstration

function createCounter() {
  let count = 0;
  return {
    increment: () => ++count,
    getCount: () => count,
  };
}
 
const counter = createCounter();
counter.increment();
counter.increment();
counter.getCount(); // 2
// `count` is not accessible from outside but survives because the closures reference it

"This is encapsulation without classes. count is truly private — no way to access it except through the returned methods."

Real-World Impact

"Closures power React hooks — every render creates a new closure, which is why hooks 'see' the state from their render. The stale closure bug happens when an effect captures a value from an old render and never updates."

The this Answer

"this in JavaScript is the only dynamically-scoped construct. It's determined by how a function is called, not where it's defined. There are four rules in order of precedence:

  1. new binding — this is the new instance
  2. Explicit binding (call/apply/bind) — this is the specified object
  3. Implicit binding — this is the object before the dot
  4. Default — undefined in strict mode, window in sloppy mode

Arrow functions are the exception — they have no own this and capture it lexically from the enclosing scope."

The Trap Question

const obj = {
  name: 'Alice',
  greet: () => `Hello, ${this.name}`,
};
obj.greet(); // "Hello, undefined"

"Arrow function captures this from the enclosing scope — which is module/global scope, not obj. This is a common mistake: arrow functions should not be used as object methods when you need this to refer to the object."

Why It Matters

"Understanding this explains why React class components needed .bind(this) in constructors, why arrow functions in class fields work without binding, and why passing obj.method as a callback loses context."

Red Flags

  • Defining closures as "a function inside a function" (too shallow)
  • Saying "this refers to the object" without specifying which binding rule
  • Not knowing arrow functions have no own this
  • Not connecting closures to React hooks / stale closure bugs